~ chicken-core (chicken-5) /manual/Module scheme
Trap1[[tags: manual]]2[[toc:]]34== Module scheme56This module provides all of CHICKEN's R5RS procedures and macros.7These descriptions are based directly on the ''Revised^5 Report on the8Algorithmic Language Scheme''.910This module is used by default, unless a program is compiled with11the {{-explicit-use}} option.1213== Expressions1415Expression types are categorized as primitive or derived. Primitive16expression types include variables and procedure calls. Derived17expression types are not semantically primitive, but can instead be18defined as macros. With the exception of quasiquote, whose macro19definition is complex, the derived expressions are classified as20library features. The distinction which R5RS makes between primitive21and derived is unimportant and does not necessarily reflect how it's22implemented in CHICKEN itself.2324=== Primitive expression types2526==== Variable references2728<macro><variable></macro><br>2930An expression consisting of a variable is a variable reference. The31value of the variable reference is the value stored in the location to32which the variable is bound. It is an error to reference an unbound33variable.3435 (define x 28)36 x ===> 283738==== Literal expressions3940<macro>(quote <datum>)</macro><br>41<macro>'<datum></macro><br>42<macro><constant></macro><br>4344(quote <datum>) evaluates to <datum>. <Datum> may be any external45representation of a Scheme object. This notation is used to include46literal constants in Scheme code.4748 (quote a) ===> a49 (quote #(a b c)) ===> #(a b c)50 (quote (+ 1 2)) ===> (+ 1 2)5152(quote <datum>) may be abbreviated as '<datum>. The two notations are53equivalent in all respects.5455 'a ===> a56 '#(a b c) ===> #(a b c)57 '() ===> ()58 '(+ 1 2) ===> (+ 1 2)59 '(quote a) ===> (quote a)60 ''a ===> (quote a)6162Numerical constants, string constants, character constants, and boolean63constants evaluate "to themselves"; they need not be quoted.6465 '"abc" ===> "abc"66 "abc" ===> "abc"67 '145932 ===> 14593268 145932 ===> 14593269 '#t ===> #t70 #t ===> #t7172It is an error to alter a constant (i.e. the value of a literal73expression) using a mutation procedure like set-car! or string-set!.74In the current implementation of CHICKEN, identical constants don't75share memory and it is possible to mutate them, but this may change in76the future.7778==== Procedure calls7980<macro>(<operator> <operand[1]> ...)</macro><br>8182A procedure call is written by simply enclosing in parentheses83expressions for the procedure to be called and the arguments to be84passed to it. The operator and operand expressions are evaluated (in an85unspecified order) and the resulting procedure is passed the resulting86arguments.8788 (+ 3 4) ===> 789 ((if #f + *) 3 4) ===> 129091A number of procedures are available as the values of variables in the92initial environment; for example, the addition and multiplication93procedures in the above examples are the values of the variables + and94*. New procedures are created by evaluating lambda95expressions. Procedure calls may return any number of values (see the96{{values}} procedure [[#Control_features|below]]).9798Procedure calls are also called combinations.99100Note: In contrast to other dialects of Lisp, the order of101evaluation is unspecified, and the operator expression and the102operand expressions are always evaluated with the same evaluation103rules.104105Note: Although the order of evaluation is otherwise unspecified,106the effect of any concurrent evaluation of the operator and operand107expressions is constrained to be consistent with some sequential108order of evaluation. The order of evaluation may be chosen109differently for each procedure call.110111Note: In many dialects of Lisp, the empty combination, (), is a112legitimate expression. In Scheme, combinations must have at least113one subexpression, so () is not a syntactically valid expression.114115==== Procedures116117<macro>(lambda <formals> <body>)</macro><br>118119Syntax: <Formals> should be a formal arguments list as described below,120and <body> should be a sequence of one or more expressions.121122Semantics: A lambda expression evaluates to a procedure. The123environment in effect when the lambda expression was evaluated is124remembered as part of the procedure. When the procedure is later called125with some actual arguments, the environment in which the lambda126expression was evaluated will be extended by binding the variables in127the formal argument list to fresh locations, the corresponding actual128argument values will be stored in those locations, and the expressions129in the body of the lambda expression will be evaluated sequentially in130the extended environment. The result(s) of the last expression in the131body will be returned as the result(s) of the procedure call.132133 (lambda (x) (+ x x)) ===> a procedure134 ((lambda (x) (+ x x)) 4) ===> 8135136 (define reverse-subtract137 (lambda (x y) (- y x)))138 (reverse-subtract 7 10) ===> 3139140 (define add4141 (let ((x 4))142 (lambda (y) (+ x y))))143 (add4 6) ===> 10144145<Formals> should have one of the following forms:146147* (<variable[1]> ...): The procedure takes a fixed number of148 arguments; when the procedure is called, the arguments will be149 stored in the bindings of the corresponding variables.150151* <variable>: The procedure takes any number of arguments; when the152 procedure is called, the sequence of actual arguments is converted153 into a newly allocated list, and the list is stored in the binding154 of the <variable>.155156* (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a157 space-delimited period precedes the last variable, then the158 procedure takes n or more arguments, where n is the number of159 formal arguments before the period (there must be at least one).160 The value stored in the binding of the last variable will be a161 newly allocated list of the actual arguments left over after all162 the other actual arguments have been matched up against the other163 formal arguments.164165It is an error for a <variable> to appear more than once in <formals>.166167 ((lambda x x) 3 4 5 6) ===> (3 4 5 6)168 ((lambda (x y . z) z)169 3 4 5 6) ===> (5 6)170171Each procedure created as the result of evaluating a lambda expression172is (conceptually) tagged with a storage location, in order to make eqv?173and eq? work on procedures.174175As an extension to R5RS, CHICKEN also supports "extended" DSSSL style176parameter lists, which allows embedded special keywords. Such a177keyword gives a special meaning to the {{<formal>}} it precedes.178DSSSL parameter lists are defined by the following grammar:179180 <parameter-list> ==> <required-parameter>*181 [#!optional <optional-parameter>*]182 [#!rest <rest-parameter>]183 [#!key <keyword-parameter>*]184 <required-parameter> ==> <ident>185 <optional-parameter> ==> <ident>186 | (<ident> <initializer>)187 <rest-parameter> ==> <ident>188 <keyword-parameter> ==> <ident>189 | (<ident> <initializer>)190 <initializer> ==> <expr>191192When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:193194* Required-parameters are bound to successive arguments starting with the first argument. It shall be an error if there are fewer arguments than required-parameters.195* Next, the optional-parameters are bound with the remaining arguments. If there are fewer arguments than optional-parameters, then the remaining optional-parameters are bound to the result of the evaluation of their corresponding <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.196* If there is a rest-parameter, then it is bound to a list containing all the remaining arguments left over after the argument bindings with required-parameters and optional-parameters have been made.197* If {{#!key}} was specified in the parameter-list, there should be an even number of remaining arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the parameter name, and the second member is the corresponding value. If the same keyword occurs more than once in the list of arguments, then the corresponding value of the first keyword is the binding value. If there is no argument for a particular keyword-parameter, then the variable is bound to the result of evaluating <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.198199Needing a special mention is the close relationship between the200rest-parameter and possible keyword-parameters. Declaring a201rest-parameter binds up all remaining arguments in a list, as202described above. These same remaining arguments are also used for203attempted matches with declared keyword-parameters, as described204above, in which case a matching keyword-parameter binds to the205corresponding value argument at the same time that both the keyword206and value arguments are added to the rest parameter list. Note that207for efficiency reasons, the keyword-parameter matching does nothing208more than simply attempt to match with pairs that may exist in the209remaining arguments. Extra arguments that don't match are simply210unused and forgotten if no rest-parameter has been declared. Because211of this, the caller of a procedure containing one or more212keyword-parameters cannot rely on any kind of system error to report213wrong keywords being passed in.214215It shall be an error for an {{<ident>}} to appear more than once in a216parameter-list.217218If there is no rest-parameter and no keyword-parameters in the parameter-list, then it shall be an error for any extra arguments to be passed to the procedure.219220221Example:222223 ((lambda x x) 3 4 5 6) => (3 4 5 6)224 ((lambda (x y #!rest z) z)225 3 4 5 6) => (5 6)226 ((lambda (x y #!optional z #!rest r #!key i (j 1))227 (list x y z i: i j: j))228 3 4 5 i: 6 i: 7) => (3 4 5 i: 6 j: 1)229230231232==== Conditionals233234<macro>(if <test> <consequent> <alternate>)</macro><br>235<macro>(if <test> <consequent>)</macro><br>236237Syntax: <Test>, <consequent>, and <alternate> may be arbitrary238expressions.239240Semantics: An if expression is evaluated as follows: first, <test> is241evaluated. If it yields a true value (see [[#Booleans|the section242about booleans]] below), then <consequent> is evaluated and its243value(s) is(are) returned. Otherwise <alternate> is evaluated and its244value(s) is(are) returned. If <test> yields a false value and no245<alternate> is specified, then the result of the expression is246unspecified.247248 (if (> 3 2) 'yes 'no) ===> yes249 (if (> 2 3) 'yes 'no) ===> no250 (if (> 3 2)251 (- 3 2)252 (+ 3 2)) ===> 1253254==== Assignments255256<macro>(set! <variable> <expression>)</macro><br>257258<Expression> is evaluated, and the resulting value is stored in the259location to which <variable> is bound. <Variable> must be bound either260in some region enclosing the set! expression or at top level. The261result of the set! expression is unspecified.262263 (define x 2)264 (+ x 1) ===> 3265 (set! x 4) ===> unspecified266 (+ x 1) ===> 5267268As an extension to R5RS, {{set!}} for unbound toplevel variables is269allowed. Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN270implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].271272=== Derived expression types273274The constructs in this section are hygienic. For reference purposes,275these macro definitions will convert most of the constructs described276in this section into the primitive constructs described in the277previous section. This does not necessarily mean that's exactly how278it's implemented in CHICKEN.279280==== Derived Conditionals281282<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>283284Syntax: Each <clause> should be of the form285286 (<test> <expression[1]> ...)287288where <test> is any expression. Alternatively, a <clause> may be of the289form290291 (<test> => <expression>)292293The last <clause> may be an "else clause," which has the form294295 (else <expression[1]> <expression[2]> ...).296297Semantics: A cond expression is evaluated by evaluating the <test>298expressions of successive <clause>s in order until one of them299evaluates to a true value (see [[#Booleans|the section about300booleans]] below). When a <test> evaluates to a true value, then the301remaining <expression>s in its <clause> are evaluated in order, and302the result(s) of the last <expression> in the <clause> is(are)303returned as the result(s) of the entire cond expression. If the304selected <clause> contains only the <test> and no <expression>s, then305the value of the <test> is returned as the result. If the selected306<clause> uses the => alternate form, then the <expression> is307evaluated. Its value must be a procedure that accepts one argument;308this procedure is then called on the value of the <test> and the309value(s) returned by this procedure is(are) returned by the cond310expression. If all <test>s evaluate to false values, and there is no311else clause, then the result of the conditional expression is312unspecified; if there is an else clause, then its <expression>s are313evaluated, and the value(s) of the last one is(are) returned.314315 (cond ((> 3 2) 'greater)316 ((< 3 2) 'less)) ===> greater317 (cond ((> 3 3) 'greater)318 ((< 3 3) 'less)319 (else 'equal)) ===> equal320 (cond ((assv 'b '((a 1) (b 2))) => cadr)321 (else #f)) ===> 2322323324As an extension to R5RS, CHICKEN also supports the325[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:326327 (<generator> <guard> => <expression>)328329In this situation, {{generator}} is ''always'' evaluated. Its330resulting value(s) are used as argument(s) for the {{guard}}331procedure. Finally, if {{guard}} returns a non-{{#f}} value, the332{{expression}} is evaluated by calling it with the result of333{{guard}}. Otherwise, evaluation procedes to the next clause.334335<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>336337Syntax: <Key> may be any expression. Each <clause> should have the form338339 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),340341where each <datum> is an external representation of some object.342Alternatively, as per R7RS, a <clause> may be of the form343344 ((<datum[1]> ...) => <expression>).345346All the <datum>s must be distinct. The last <clause> may be an347"else clause," which has one of the following two forms:348349 (else <expression[1]> <expression[2]> ...)350 (else => <expression>). ; R7RS extension351352Semantics: A case expression is evaluated as follows. <Key> is353evaluated and its result is compared against each <datum>. If the354result of evaluating <key> is equivalent (in the sense of {{eqv?}};355see [[#Equivalence_predicates|below]]) to a <datum>, then the356expressions in the corresponding <clause> are evaluated from left to357right and the result(s) of the last expression in the <clause> is(are)358returned as the result(s) of the case expression. If the selected359<clause> uses the => alternate form (an R7RS extension), then the360<expression> is evaluated. Its value must be a procedure that accepts361one argument; this procedure is then called on the value of the <key>362and the value(s) returned by this procedure is(are) returned by the363case expression. If the result of evaluating <key> is different from364every <datum>, then if there is an else clause its expressions are365evaluated and the result(s) of the last is(are) the result(s) of the366case expression; otherwise the result of the case expression is367unspecified.368369 (case (* 2 3)370 ((2 3 5 7) 'prime)371 ((1 4 6 8 9) 'composite)) ===> composite372 (case (car '(c d))373 ((a) 'a)374 ((b) 'b)) ===> unspecified375 (case (car '(c d))376 ((a e i o u) 'vowel)377 ((w y) 'semivowel)378 (else 'consonant)) ===> consonant379380<macro>(and <test[1]> ...)</macro><br>381382The <test> expressions are evaluated from left to right, and the value383of the first expression that evaluates to a false value (see384[[#Booleans|the section about booleans]]) is returned. Any remaining385expressions are not evaluated. If all the expressions evaluate to true386values, the value of the last expression is returned. If there are no387expressions then #t is returned.388389 (and (= 2 2) (> 2 1)) ===> #t390 (and (= 2 2) (< 2 1)) ===> #f391 (and 1 2 'c '(f g)) ===> (f g)392 (and) ===> #t393394<macro>(or <test[1]> ...)</macro><br>395396The <test> expressions are evaluated from left to right, and the value397of the first expression that evaluates to a true value (see398[[#Booleans|the section about booleans]]) is returned. Any remaining399expressions are not evaluated. If all expressions evaluate to false400values, the value of the last expression is returned. If there are no401expressions then #f is returned.402403 (or (= 2 2) (> 2 1)) ===> #t404 (or (= 2 2) (< 2 1)) ===> #t405 (or #f #f #f) ===> #f406 (or (memq 'b '(a b c))407 (/ 3 0)) ===> (b c)408409==== Binding constructs410411The three binding constructs let, let*, and letrec give Scheme a block412structure, like Algol 60. The syntax of the three constructs is413identical, but they differ in the regions they establish for their414variable bindings. In a let expression, the initial values are computed415before any of the variables become bound; in a let* expression, the416bindings and evaluations are performed sequentially; while in a letrec417expression, all the bindings are in effect while their initial values418are being computed, thus allowing mutually recursive definitions.419420<macro>(let <bindings> <body>)</macro><br>421422Syntax: <Bindings> should have the form423424 ((<variable[1]> <init[1]>) ...),425426where each <init> is an expression, and <body> should be a sequence of427one or more expressions. It is an error for a <variable> to appear more428than once in the list of variables being bound.429430Semantics: The <init>s are evaluated in the current environment (in431some unspecified order), the <variable>s are bound to fresh locations432holding the results, the <body> is evaluated in the extended433environment, and the value(s) of the last expression of <body> is(are)434returned. Each binding of a <variable> has <body> as its region.435436 (let ((x 2) (y 3))437 (* x y)) ===> 6438439 (let ((x 2) (y 3))440 (let ((x 7)441 (z (+ x y)))442 (* z x))) ===> 35443444See also "named let", [[#Iteration|below]].445446<macro>(let* <bindings> <body>)</macro><br>447448Syntax: <Bindings> should have the form449450 ((<variable[1]> <init[1]>) ...),451452and <body> should be a sequence of one or more expressions.453454Semantics: Let* is similar to let, but the bindings are performed455sequentially from left to right, and the region of a binding indicated456by (<variable> <init>) is that part of the let* expression to the right457of the binding. Thus the second binding is done in an environment in458which the first binding is visible, and so on.459460 (let ((x 2) (y 3))461 (let* ((x 7)462 (z (+ x y)))463 (* z x))) ===> 70464465<macro>(letrec <bindings> <body>)</macro><br>466467Syntax: <Bindings> should have the form468469 ((<variable[1]> <init[1]>) ...),470471and <body> should be a sequence of one or more expressions. It is an472error for a <variable> to appear more than once in the list of473variables being bound.474475Semantics: The <variable>s are bound to fresh locations holding476undefined values, the <init>s are evaluated in the resulting477environment (in some unspecified order), each <variable> is assigned to478the result of the corresponding <init>, the <body> is evaluated in the479resulting environment, and the value(s) of the last expression in480<body> is(are) returned. Each binding of a <variable> has the entire481letrec expression as its region, making it possible to define mutually482recursive procedures.483484 (letrec ((even?485 (lambda (n)486 (if (zero? n)487 #t488 (odd? (- n 1)))))489 (odd?490 (lambda (n)491 (if (zero? n)492 #f493 (even? (- n 1))))))494 (even? 88))495 ===> #t496497One restriction on letrec is very important: it must be possible to498evaluate each <init> without assigning or referring to the value of any499<variable>. If this restriction is violated, then it is an error. The500restriction is necessary because Scheme passes arguments by value501rather than by name. In the most common uses of letrec, all the <init>s502are lambda expressions and the restriction is satisfied automatically.503504==== Sequencing505506<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>507508The <expression>s are evaluated sequentially from left to right, and509the value(s) of the last <expression> is(are) returned. This expression510type is used to sequence side effects such as input and output.511512 (define x 0)513514 (begin (set! x 5)515 (+ x 1)) ===> 6516517 (begin (display "4 plus 1 equals ")518 (display (+ 4 1))) ===> unspecified519 and prints 4 plus 1 equals 5520521As an extension to R5RS, CHICKEN also allows {{(begin)}} without body522expressions in any context, not just at toplevel. This simply523evaluates to the unspecified value.524525526==== Iteration527528<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>529530Do is an iteration construct. It specifies a set of variables to be531bound, how they are to be initialized at the start, and how they are to532be updated on each iteration. When a termination condition is met, the533loop exits after evaluating the <expression>s.534535Do expressions are evaluated as follows: The <init> expressions are536evaluated (in some unspecified order), the <variable>s are bound to537fresh locations, the results of the <init> expressions are stored in538the bindings of the <variable>s, and then the iteration phase begins.539540Each iteration begins by evaluating <test>; if the result is false541(see [[#Booleans|the section about booleans]]), then the <command>542expressions are evaluated in order for effect, the <step> expressions543are evaluated in some unspecified order, the <variable>s are bound to544fresh locations, the results of the <step>s are stored in the bindings545of the <variable>s, and the next iteration begins.546547If <test> evaluates to a true value, then the <expression>s are548evaluated from left to right and the value(s) of the last <expression>549is(are) returned. If no <expression>s are present, then the value of550the do expression is unspecified.551552The region of the binding of a <variable> consists of the entire do553expression except for the <init>s. It is an error for a <variable> to554appear more than once in the list of do variables.555556A <step> may be omitted, in which case the effect is the same as if557(<variable> <init> <variable>) had been written instead of (<variable>558<init>).559560 (do ((vec (make-vector 5))561 (i 0 (+ i 1)))562 ((= i 5) vec)563 (vector-set! vec i i)) ===> #(0 1 2 3 4)564565 (let ((x '(1 3 5 7 9)))566 (do ((x x (cdr x))567 (sum 0 (+ sum (car x))))568 ((null? x) sum))) ===> 25569570<macro>(let <variable> <bindings> <body>)</macro><br>571572"Named let" is a variant on the syntax of let which provides a more573general looping construct than do and may also be used to express574recursions. It has the same syntax and semantics as ordinary let except575that <variable> is bound within <body> to a procedure whose formal576arguments are the bound variables and whose body is <body>. Thus the577execution of <body> may be repeated by invoking the procedure named by578<variable>.579580 (let loop ((numbers '(3 -2 1 6 -5))581 (nonneg '())582 (neg '()))583 (cond ((null? numbers) (list nonneg neg))584 ((>= (car numbers) 0)585 (loop (cdr numbers)586 (cons (car numbers) nonneg)587 neg))588 ((< (car numbers) 0)589 (loop (cdr numbers)590 nonneg591 (cons (car numbers) neg)))))592 ===> ((6 1 3) (-5 -2))593594==== Delayed evaluation595596<macro>(delay <expression>)</macro><br>597598The delay construct is used together with the procedure force to599implement lazy evaluation or call by need. {{(delay <expression>)}}600returns an object called a promise which at some point in the future601may be asked (by the force procedure) to evaluate {{<expression>}},602and deliver the resulting value. The {{<expression>}} may return603multiple values, which will be correctly memoized and returned by604subsequent calls to {{force}}. This is a CHICKEN extension to R5RS.605606See the description of {{force}} (under [[#control-features|Control607features]], below) for a more complete description of {{delay}}.608609CHICKEN also supports the R7RS {{delay-force}} syntax which allows for610iterative lazy algorithms to be expressed in bounded space. See the611[[Module (chicken base)#lazy-evaluation|Lazy evaluation section]] in612the (chicken base) module documentation for more information.613614615==== Quasiquotation616617<macro>(quasiquote <qq template>)</macro><br>618<macro>`<qq template></macro><br>619620"Backquote" or "quasiquote" expressions are useful for constructing621a list or vector structure when most but not all of the desired622structure is known in advance. If no commas appear within the <qq623template>, the result of evaluating `<qq template> is equivalent to the624result of evaluating '<qq template>. If a comma appears within the <qq625template>, however, the expression following the comma is evaluated626("unquoted") and its result is inserted into the structure instead of627the comma and the expression. If a comma appears followed immediately628by an at-sign (@), then the following expression must evaluate to a629list; the opening and closing parentheses of the list are then630"stripped away" and the elements of the list are inserted in place of631the comma at-sign expression sequence. A comma at-sign should only632appear within a list or vector <qq template>.633634 `(list ,(+ 1 2) 4) ===> (list 3 4)635 (let ((name 'a)) `(list ,name ',name))636 ===> (list a (quote a))637 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)638 ===> (a 3 4 5 6 b)639 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))640 ===> ((foo 7) . cons)641 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)642 ===> #(10 5 2 4 3 8)643644Quasiquote forms may be nested. Substitutions are made only for645unquoted components appearing at the same nesting level as the646outermost backquote. The nesting level increases by one inside each647successive quasiquotation, and decreases by one inside each648unquotation.649650 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)651 ===> (a `(b ,(+ 1 2) ,(foo 4 d) e) f)652 (let ((name1 'x)653 (name2 'y))654 `(a `(b ,,name1 ,',name2 d) e))655 ===> (a `(b ,x ,'y d) e)656657The two notations `<qq template> and (quasiquote <qq template>) are658identical in all respects. ,<expression> is identical to (unquote659<expression>), and ,@<expression> is identical to (unquote-splicing660<expression>). The external syntax generated by write for two-element661lists whose car is one of these symbols may vary between662implementations.663664 (quasiquote (list (unquote (+ 1 2)) 4))665 ===> (list 3 4)666 '(quasiquote (list (unquote (+ 1 2)) 4))667 ===> `(list ,(+ 1 2) 4)668 i.e., (quasiquote (list (unquote (+ 1 2)) 4))669670Unpredictable behavior can result if any of the symbols quasiquote,671unquote, or unquote-splicing appear in positions within a <qq template>672otherwise than as described above.673674=== Macros675676Scheme programs can define and use new derived expression types, called677macros. Program-defined expression types have the syntax678679 (<keyword> <datum> ...)680681where <keyword> is an identifier that uniquely determines the682expression type. This identifier is called the syntactic keyword, or683simply keyword, of the macro. The number of the <datum>s, and their684syntax, depends on the expression type.685686Each instance of a macro is called a use of the macro. The set of rules687that specifies how a use of a macro is transcribed into a more688primitive expression is called the transformer of the macro.689690The macro definition facility consists of two parts:691692* A set of expressions used to establish that certain identifiers are693 macro keywords, associate them with macro transformers, and control694 the scope within which a macro is defined, and695696* a pattern language for specifying macro transformers.697698The syntactic keyword of a macro may shadow variable bindings, and699local variable bindings may shadow keyword bindings. All macros defined700using the pattern language are "hygienic" and "referentially701transparent" and thus preserve Scheme's lexical scoping:702703* If a macro transformer inserts a binding for an identifier704 (variable or keyword), the identifier will in effect be renamed705 throughout its scope to avoid conflicts with other identifiers.706 Note that a define at top level may or may not introduce a binding;707 this depends on whether the binding already existed before (in which708 case its value will be overridden).709710* If a macro transformer inserts a free reference to an identifier,711 the reference refers to the binding that was visible where the712 transformer was specified, regardless of any local bindings that713 may surround the use of the macro.714715==== Binding constructs for syntactic keywords716717Let-syntax and letrec-syntax are analogous to let and letrec, but they718bind syntactic keywords to macro transformers instead of binding719variables to locations that contain values. Syntactic keywords may also720be bound at top level.721722<macro>(let-syntax <bindings> <body>)</macro><br>723724Syntax: <Bindings> should have the form725726 ((<keyword> <transformer spec>) ...)727728Each <keyword> is an identifier, each <transformer spec> is an instance729of syntax-rules, and <body> should be a sequence of one or more730expressions. It is an error for a <keyword> to appear more than once in731the list of keywords being bound.732733Semantics: The <body> is expanded in the syntactic environment obtained734by extending the syntactic environment of the let-syntax expression735with macros whose keywords are the <keyword>s, bound to the specified736transformers. Each binding of a <keyword> has <body> as its region.737738 (let-syntax ((when (syntax-rules ()739 ((when test stmt1 stmt2 ...)740 (if test741 (begin stmt1742 stmt2 ...))))))743 (let ((if #t))744 (when if (set! if 'now))745 if)) ===> now746747 (let ((x 'outer))748 (let-syntax ((m (syntax-rules () ((m) x))))749 (let ((x 'inner))750 (m)))) ===> outer751752<macro>(letrec-syntax <bindings> <body>)</macro><br>753754Syntax: Same as for let-syntax.755756Semantics: The <body> is expanded in the syntactic environment obtained757by extending the syntactic environment of the letrec-syntax expression758with macros whose keywords are the <keyword>s, bound to the specified759transformers. Each binding of a <keyword> has the <bindings> as well as760the <body> within its region, so the transformers can transcribe761expressions into uses of the macros introduced by the letrec-syntax762expression.763764 (letrec-syntax765 ((my-or (syntax-rules ()766 ((my-or) #f)767 ((my-or e) e)768 ((my-or e1 e2 ...)769 (let ((temp e1))770 (if temp771 temp772 (my-or e2 ...)))))))773 (let ((x #f)774 (y 7)775 (temp 8)776 (let odd?)777 (if even?))778 (my-or x779 (let temp)780 (if y)781 y))) ===> 7782783==== Pattern language784785A <transformer spec> has the following form:786787 (syntax-rules <literals> <syntax rule> ...)788789Syntax: <Literals> is a list of identifiers and each <syntax rule>790should be of the form791792 (<pattern> <template>)793794The <pattern> in a <syntax rule> is a list <pattern> that begins with795the keyword for the macro.796797A <pattern> is either an identifier, a constant, or one of the798following799800 (<pattern> ...)801 (<pattern> <pattern> ... . <pattern>)802 (<pattern> ... <pattern> <ellipsis>)803 #(<pattern> ...)804 #(<pattern> ... <pattern> <ellipsis>)805806and a template is either an identifier, a constant, or one of the807following808809 (<element> ...)810 (<element> <element> ... . <template>)811 #(<element> ...)812813where an <element> is a <template> optionally followed by an <ellipsis>814and an <ellipsis> is the identifier "..." (which cannot be used as an815identifier in either a template or a pattern).816817Semantics: An instance of syntax-rules produces a new macro transformer818by specifying a sequence of hygienic rewrite rules. A use of a macro819whose keyword is associated with a transformer specified by820syntax-rules is matched against the patterns contained in the <syntax821rule>s, beginning with the leftmost <syntax rule>. When a match is822found, the macro use is transcribed hygienically according to the823template.824825An identifier that appears in the pattern of a <syntax rule> is a826pattern variable, unless it is the keyword that begins the pattern, is827listed in <literals>, or is the identifier "...". Pattern variables828match arbitrary input elements and are used to refer to elements of the829input in the template. It is an error for the same pattern variable to830appear more than once in a <pattern>.831832The keyword at the beginning of the pattern in a <syntax rule> is not833involved in the matching and is not considered a pattern variable or834literal identifier.835836Rationale: The scope of the keyword is determined by the837expression or syntax definition that binds it to the associated838macro transformer. If the keyword were a pattern variable or839literal identifier, then the template that follows the pattern840would be within its scope regardless of whether the keyword were841bound by let-syntax or by letrec-syntax.842843Identifiers that appear in <literals> are interpreted as literal844identifiers to be matched against corresponding subforms of the input.845A subform in the input matches a literal identifier if and only if it846is an identifier and either both its occurrence in the macro expression847and its occurrence in the macro definition have the same lexical848binding, or the two identifiers are equal and both have no lexical849binding.850851A subpattern followed by ... can match zero or more elements of the852input. It is an error for ... to appear in <literals>. Within a pattern853the identifier ... must follow the last element of a nonempty sequence854of subpatterns.855856More formally, an input form F matches a pattern P if and only if:857858* P is a non-literal identifier; or859860* P is a literal identifier and F is an identifier with the same861 binding; or862863* P is a list (P[1] ... P[n]) and F is a list of n forms that match P864 [1] through P[n], respectively; or865866* P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list867 or improper list of n or more forms that match P[1] through P[n],868 respectively, and whose nth "cdr" matches P[n+1]; or869870* P is of the form (P[1] ... P[n] P[n+1] <ellipsis>) where <ellipsis>871 is the identifier ... and F is a proper list of at least n forms,872 the first n of which match P[1] through P[n], respectively, and873 each remaining element of F matches P[n+1]; or874875* P is a vector of the form #(P[1] ... P[n]) and F is a vector of n876 forms that match P[1] through P[n]; or877878* P is of the form #(P[1] ... P[n] P[n+1] <ellipsis>) where879 <ellipsis> is the identifier ... and F is a vector of n or more880 forms the first n of which match P[1] through P[n], respectively,881 and each remaining element of F matches P[n+1]; or882883* P is a datum and F is equal to P in the sense of the equal?884 procedure.885886It is an error to use a macro keyword, within the scope of its binding,887in an expression that does not match any of the patterns.888889When a macro use is transcribed according to the template of the890matching <syntax rule>, pattern variables that occur in the template891are replaced by the subforms they match in the input. Pattern variables892that occur in subpatterns followed by one or more instances of the893identifier ... are allowed only in subtemplates that are followed by as894many instances of .... They are replaced in the output by all of the895subforms they match in the input, distributed as indicated. It is an896error if the output cannot be built up as specified.897898Identifiers that appear in the template but are not pattern variables899or the identifier ... are inserted into the output as literal900identifiers. If a literal identifier is inserted as a free identifier901then it refers to the binding of that identifier within whose scope the902instance of syntax-rules appears. If a literal identifier is inserted903as a bound identifier then it is in effect renamed to prevent904inadvertent captures of free identifiers.905906As an example, if let and cond are defined as usual, then they are907hygienic (as required) and the following is not an error.908909 (let ((=> #f))910 (cond (#t => 'ok))) ===> ok911912The macro transformer for cond recognizes => as a local variable, and913hence an expression, and not as the top-level identifier =>, which the914macro transformer treats as a syntactic keyword. Thus the example915expands into916917 (let ((=> #f))918 (if #t (begin => 'ok)))919920instead of921922 (let ((=> #f))923 (let ((temp #t))924 (if temp ('ok temp))))925926which would result in an invalid procedure call.927928== Program structure929930=== Programs931932A Scheme program consists of a sequence of expressions, definitions,933and syntax definitions. Expressions are described in chapter 4;934definitions and syntax definitions are the subject of the rest of the935present chapter.936937Programs are typically stored in files or entered interactively to a938running Scheme system, although other paradigms are possible;939questions of user interface lie outside the scope of this940report. (Indeed, Scheme would still be useful as a notation for941expressing computational methods even in the absence of a mechanical942implementation.)943944Definitions and syntax definitions occurring at the top level of a945program can be interpreted declaratively. They cause bindings to be946created in the top level environment or modify the value of existing947top-level bindings. Expressions occurring at the top level of a948program are interpreted imperatively; they are executed in order when949the program is invoked or loaded, and typically perform some kind of950initialization.951952At the top level of a program (begin <form1> ...) is equivalent to the953sequence of expressions, definitions, and syntax definitions that form954the body of the begin.955956=== Definitions957958Definitions are valid in some, but not all, contexts where expressions959are allowed. They are valid only at the top level of a <program> and960at the beginning of a <body>.961962A definition should have one of the following forms:963964<macro>(define <variable> <expression>)</macro><br>965<macro>(define (<variable> <formals>) <body>)</macro><br>966967<Formals> should be either a sequence of zero or more variables, or a968sequence of one or more variables followed by a space-delimited period969and another variable (as in a lambda expression). This form is970equivalent to971972 (define <variable>973 (lambda (<formals>) <body>)).974975<macro>(define <variable>)</macro>976977This form is a CHICKEN extension to R5RS, and is equivalent to978979 (define <variable> (void))980981<macro>(define (<variable> . <formal>) <body>)</macro><br>982983<Formal> should be a single variable. This form is equivalent to984985 (define <variable>986 (lambda <formal> <body>)).987988<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>989990As an extension to R5RS, CHICKEN allows ''curried'' definitions, where991the variable name may also be a list specifying a name and a nested992lambda list. For example,993994 (define ((make-adder x) y) (+ x y))995996is equivalent to997998 (define (make-adder x) (lambda (y) (+ x y))).9991000This type of curried definition can be nested arbitrarily and combined1001with dotted tail notation or DSSSL keywords.10021003==== Top level definitions10041005At the top level of a program, a definition10061007 (define <variable> <expression>)10081009has essentially the same effect as the assignment expression10101011 (set! <variable> <expression>)10121013if <variable> is bound. If <variable> is not bound, however, then the1014definition will bind <variable> to a new location before performing1015the assignment, whereas it would be an error to perform a set! on an1016unbound variable in standard Scheme. In CHICKEN, {{set!}} at toplevel1017has the same effect as a definition, unless inside a module, in which1018case it is an error.10191020 (define add31021 (lambda (x) (+ x 3)))1022 (add3 3) ===> 61023 (define first car)1024 (first '(1 2)) ===> 110251026Some implementations of Scheme use an initial environment in which all1027possible variables are bound to locations, most of which contain1028undefined values. Top level definitions in such an implementation are1029truly equivalent to assignments. In CHICKEN, attempting to evaluate1030an unbound identifier will result in an error, but you ''can'' use1031{{set!}} to bind an initial value to it.10321033==== Internal definitions10341035Definitions may occur at the beginning of a <body> (that is, the body1036of a lambda, let, let*, letrec, let-syntax, or letrec-syntax1037expression or that of a definition of an appropriate form). Such1038definitions are known as internal definitions as opposed to the top1039level definitions described above. The variable defined by an internal1040definition is local to the <body>. That is, <variable> is bound rather1041than assigned, and the region of the binding is the entire <body>. For1042example,10431044 (let ((x 5))1045 (define foo (lambda (y) (bar x y)))1046 (define bar (lambda (a b) (+ (* a b) a)))1047 (foo (+ x 3))) ===> 4510481049A <body> containing internal definitions can always be converted into1050a completely equivalent letrec expression. For example, the let1051expression in the above example is equivalent to10521053 (let ((x 5))1054 (letrec ((foo (lambda (y) (bar x y)))1055 (bar (lambda (a b) (+ (* a b) a))))1056 (foo (+ x 3))))10571058Just as for the equivalent letrec expression, it must be possible to1059evaluate each <expression> of every internal definition in a <body>1060without assigning or referring to the value of any <variable> being1061defined.10621063Wherever an internal definition may occur (begin <definition1> ...) is1064equivalent to the sequence of definitions that form the body of the1065begin.10661067CHICKEN extends the R5RS semantics by allowing internal definitions1068everywhere, and not only at the beginning of a body. A set of internal1069definitions is equivalent to a {{letrec}} form enclosing all following1070expressions in the body:10711072 (let ((foo 123))1073 (bar)1074 (define foo 456)1075 (baz foo) )10761077expands into10781079 (let ((foo 123))1080 (bar)1081 (letrec ((foo 456))1082 (baz foo) ) )10831084Local sequences of {{define-syntax}} forms are translated into1085equivalent {{letrec-syntax}} forms that enclose the following forms as1086the body of the expression.108710881089=== Syntax definitions10901091Syntax definitions are valid only at the top level of a1092<program>. They have the following form:10931094<macro>(define-syntax <keyword> <transformer spec>)</macro>10951096{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should1097be an instance of {{syntax-rules}}. Note that CHICKEN also supports1098{{er-macro-transformer}} and {{ir-macro-transformer}} here. For more1099information see [[Module (chicken syntax)|the (chicken syntax) module]].11001101The top-level syntactic environment is extended by binding the1102<keyword> to the specified transformer.11031104In standard Scheme, there is no define-syntax analogue of internal1105definitions in, but CHICKEN allows these as an extension to the1106standard. This means {{define-syntax}} may be used to define local1107macros that are visible throughout the rest of the body in which the1108definition occurred, i.e.11091110 (let ()1111 ...1112 (define-syntax foo ...)1113 (define-syntax bar ...)1114 ...)11151116is expanded into11171118 (let ()1119 ...1120 (letrec-syntax ((foo ...) (bar ...))1121 ...) )11221123{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]1124in allowing the ellipsis identifier to be user-defined by passing it as the first1125argument to the {{syntax-rules}} form. Also, "tail" patterns of the form11261127 (syntax-rules ()1128 ((_ (a b ... c)1129 ...11301131are supported.11321133The effect of destructively modifying the s-expression passed to a1134transformer procedure is undefined.11351136Although macros may expand into definitions and syntax definitions in1137any context that permits them, it is an error for a definition or1138syntax definition to shadow a syntactic keyword whose meaning is1139needed to determine whether some form in the group of forms that1140contains the shadowing definition is in fact a definition, or, for1141internal definitions, is needed to determine the boundary between the1142group and the expressions that follow the group. For example, the1143following are errors:11441145 (define define 3)11461147 (begin (define begin list))11481149 (let-syntax1150 ((foo (syntax-rules ()1151 ((foo (proc args ...) body ...)1152 (define proc1153 (lambda (args ...)1154 body ...))))))1155 (let ((x 3))1156 (foo (plus x y) (+ x y))1157 (define foo x)1158 (plus foo x)))11591160== Standard procedures11611162This chapter describes Scheme's built-in procedures. The initial (or1163"top level") Scheme environment starts out with a number of variables1164bound to locations containing useful values, most of which are1165primitive procedures that manipulate data. For example, the variable1166abs is bound to (a location initially containing) a procedure of one1167argument that computes the absolute value of a number, and the variable1168+ is bound to a procedure that computes sums. Built-in procedures that1169can easily be written in terms of other built-in procedures are1170identified as "library procedures".11711172A program may use a top-level definition to bind any variable. It may1173subsequently alter any such binding by an assignment (see1174[[#assignments|assignments]], above). These operations do1175not modify the behavior of Scheme's built-in procedures. Altering any1176top-level binding that has not been introduced by a definition has an1177unspecified effect on the behavior of the built-in procedures.11781179=== Equivalence predicates11801181A predicate is a procedure that always returns a boolean value (#t or #f).1182An equivalence predicate is the computational analogue of a1183mathematical equivalence relation (it is symmetric, reflexive, and1184transitive). Of the equivalence predicates described in this section,1185eq? is the finest or most discriminating, and equal? is the coarsest.1186eqv? is slightly less discriminating than eq?.11871188<procedure>(eqv? obj[1] obj[2])</procedure><br>11891190The eqv? procedure defines a useful equivalence relation on objects.1191Briefly, it returns #t if obj[1] and obj[2] should normally be regarded1192as the same object. This relation is left slightly open to1193interpretation, but the following partial specification of eqv? holds1194for all implementations of Scheme.11951196The eqv? procedure returns #t if:11971198* obj[1] and obj[2] are both #t or both #f.11991200* obj[1] and obj[2] are both symbols and12011202 (string=? (symbol->string obj1)1203 (symbol->string obj2))1204 ===> #t12051206Note: This assumes that neither obj[1] nor obj[2] is an "uninterned1207symbol" as alluded to in the section on [[#symbols|symbols]]. This1208report does not presume to specify the behavior of eqv? on1209implementation-dependent extensions.12101211* obj[1] and obj[2] are both numbers, are numerically equal (see =,1212 under [[#numerical-operations|numerical operations]]), and are1213 either both exact or both inexact.12141215* obj[1] and obj[2] are both characters and are the same character1216 according to the char=? procedure (see "[[#characters|characters]]").12171218* both obj[1] and obj[2] are the empty list.12191220* obj[1] and obj[2] are pairs, vectors, or strings that denote the1221 same locations in the store.12221223* obj[1] and obj[2] are procedures whose location tags are equal1224 (see "[[#procedures|procedures]]").12251226The eqv? procedure returns #f if:12271228* obj[1] and obj[2] are of different types.12291230* one of obj[1] and obj[2] is #t but the other is #f.12311232* obj[1] and obj[2] are symbols but12331234 (string=? (symbol->string obj[1])1235 (symbol->string obj[2]))1236 ===> #f12371238* one of obj[1] and obj[2] is an exact number but the other is an1239 inexact number.12401241* obj[1] and obj[2] are numbers for which the = procedure returns #f.12421243* obj[1] and obj[2] are characters for which the char=? procedure1244 returns #f.12451246* one of obj[1] and obj[2] is the empty list but the other is not.12471248* obj[1] and obj[2] are pairs, vectors, or strings that denote1249 distinct locations.12501251* obj[1] and obj[2] are procedures that would behave differently1252 (return different value(s) or have different side effects) for some1253 arguments.12541255 (eqv? 'a 'a) ===> #t1256 (eqv? 'a 'b) ===> #f1257 (eqv? 2 2) ===> #t1258 (eqv? '() '()) ===> #t1259 (eqv? 100000000 100000000) ===> #t1260 (eqv? (cons 1 2) (cons 1 2)) ===> #f1261 (eqv? (lambda () 1)1262 (lambda () 2)) ===> #f1263 (eqv? #f 'nil) ===> #f1264 (let ((p (lambda (x) x)))1265 (eqv? p p)) ===> #t12661267The following examples illustrate cases in which the above rules do not1268fully specify the behavior of eqv?. All that can be said about such1269cases is that the value returned by eqv? must be a boolean.12701271 (eqv? "" "") ===> unspecified1272 (eqv? '#() '#()) ===> unspecified1273 (eqv? (lambda (x) x)1274 (lambda (x) x)) ===> unspecified1275 (eqv? (lambda (x) x)1276 (lambda (y) y)) ===> unspecified12771278The next set of examples shows the use of eqv? with procedures that1279have local state. Gen-counter must return a distinct procedure every1280time, since each procedure has its own internal counter. Gen-loser,1281however, returns equivalent procedures each time, since the local state1282does not affect the value or side effects of the procedures.12831284 (define gen-counter1285 (lambda ()1286 (let ((n 0))1287 (lambda () (set! n (+ n 1)) n))))1288 (let ((g (gen-counter)))1289 (eqv? g g)) ===> #t1290 (eqv? (gen-counter) (gen-counter))1291 ===> #f1292 (define gen-loser1293 (lambda ()1294 (let ((n 0))1295 (lambda () (set! n (+ n 1)) 27))))1296 (let ((g (gen-loser)))1297 (eqv? g g)) ===> #t1298 (eqv? (gen-loser) (gen-loser))1299 ===> unspecified13001301 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))1302 (g (lambda () (if (eqv? f g) 'both 'g))))1303 (eqv? f g))1304 ===> unspecified13051306 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))1307 (g (lambda () (if (eqv? f g) 'g 'both))))1308 (eqv? f g))1309 ===> #f13101311Since it is an error to modify constant objects (those returned by1312literal expressions), implementations are permitted, though not1313required, to share structure between constants where appropriate. Thus1314the value of eqv? on constants is sometimes implementation-dependent.13151316 (eqv? '(a) '(a)) ===> unspecified1317 (eqv? "a" "a") ===> unspecified1318 (eqv? '(b) (cdr '(a b))) ===> unspecified1319 (let ((x '(a)))1320 (eqv? x x)) ===> #t13211322Rationale: The above definition of eqv? allows implementations1323latitude in their treatment of procedures and literals:1324implementations are free either to detect or to fail to detect that1325two procedures or two literals are equivalent to each other, and1326can decide whether or not to merge representations of equivalent1327objects by using the same pointer or bit pattern to represent both.13281329<procedure>(eq? obj[1] obj[2])</procedure><br>13301331Eq? is similar to eqv? except that in some cases it is capable of1332discerning distinctions finer than those detectable by eqv?.13331334Eq? and eqv? are guaranteed to have the same behavior on symbols,1335booleans, the empty list, pairs, procedures, and non-empty strings and1336vectors. Eq?'s behavior on numbers and characters is1337implementation-dependent, but it will always return either true or1338false, and will return true only when eqv? would also return true. Eq?1339may also behave differently from eqv? on empty vectors and empty1340strings.13411342 (eq? 'a 'a) ===> #t1343 (eq? '(a) '(a)) ===> unspecified1344 (eq? (list 'a) (list 'a)) ===> #f1345 (eq? "a" "a") ===> unspecified1346 (eq? "" "") ===> unspecified1347 (eq? '() '()) ===> #t1348 (eq? 2 2) ===> unspecified1349 (eq? #\A #\A) ===> unspecified1350 (eq? car car) ===> #t1351 (let ((n (+ 2 3)))1352 (eq? n n)) ===> unspecified1353 (let ((x '(a)))1354 (eq? x x)) ===> #t1355 (let ((x '#()))1356 (eq? x x)) ===> #t1357 (let ((p (lambda (x) x)))1358 (eq? p p)) ===> #t13591360Rationale: It will usually be possible to implement eq? much more1361efficiently than eqv?, for example, as a simple pointer comparison1362instead of as some more complicated operation. One reason is that1363it may not be possible to compute eqv? of two numbers in constant1364time, whereas eq? implemented as pointer comparison will always1365finish in constant time. Eq? may be used like eqv? in applications1366using procedures to implement objects with state since it obeys the1367same constraints as eqv?.13681369<procedure>(equal? obj[1] obj[2])</procedure><br>13701371Equal? recursively compares the contents of pairs, vectors, and1372strings, applying eqv? on other objects such as numbers and symbols. A1373rule of thumb is that objects are generally equal? if they print the1374same. Equal? may fail to terminate if its arguments are circular data1375structures.13761377 (equal? 'a 'a) ===> #t1378 (equal? '(a) '(a)) ===> #t1379 (equal? '(a (b) c)1380 '(a (b) c)) ===> #t1381 (equal? "abc" "abc") ===> #t1382 (equal? 2 2) ===> #t1383 (equal? (make-vector 5 'a)1384 (make-vector 5 'a)) ===> #t1385 (equal? (lambda (x) x)1386 (lambda (y) y)) ===> unspecified13871388=== Numbers13891390Numerical computation has traditionally been neglected by the Lisp1391community. Until Common Lisp there was no carefully thought out1392strategy for organizing numerical computation, and with the exception1393of the MacLisp system [20] little effort was made to execute numerical1394code efficiently. This report recognizes the excellent work of the1395Common Lisp committee and accepts many of their recommendations. In1396some ways this report simplifies and generalizes their proposals in a1397manner consistent with the purposes of Scheme.13981399It is important to distinguish between the mathematical numbers, the1400Scheme numbers that attempt to model them, the machine representations1401used to implement the Scheme numbers, and notations used to write1402numbers. This report uses the types number, complex, real, rational,1403and integer to refer to both mathematical numbers and Scheme numbers.1404Machine representations such as fixed point and floating point are1405referred to by names such as fixnum and flonum.14061407==== Numerical types14081409Mathematically, numbers may be arranged into a tower of subtypes in1410which each level is a subset of the level above it:14111412 number1413 complex1414 real1415 rational1416 integer14171418For example, 3 is an integer. Therefore 3 is also a rational, a real,1419and a complex. The same is true of the Scheme numbers that model 3. For1420Scheme numbers, these types are defined by the predicates number?,1421complex?, real?, rational?, and integer?.14221423There is no simple relationship between a number's type and its1424representation inside a computer. Although most implementations of1425Scheme will offer at least two different representations of 3, these1426different representations denote the same integer.14271428Scheme's numerical operations treat numbers as abstract data, as1429independent of their representation as possible. Although an1430implementation of Scheme may use fixnum, flonum, and perhaps other1431representations for numbers, this should not be apparent to a casual1432programmer writing simple programs.14331434It is necessary, however, to distinguish between numbers that are1435represented exactly and those that may not be. For example, indexes1436into data structures must be known exactly, as must some polynomial1437coefficients in a symbolic algebra system. On the other hand, the1438results of measurements are inherently inexact, and irrational numbers1439may be approximated by rational and therefore inexact approximations.1440In order to catch uses of inexact numbers where exact numbers are1441required, Scheme explicitly distinguishes exact from inexact numbers.1442This distinction is orthogonal to the dimension of type.14431444==== Exactness14451446Scheme numbers are either exact or inexact. A number is exact if it was1447written as an exact constant or was derived from exact numbers using1448only exact operations. A number is inexact if it was written as an1449inexact constant, if it was derived using inexact ingredients, or if it1450was derived using inexact operations. Thus inexactness is a contagious1451property of a number. If two implementations produce exact results for1452a computation that did not involve inexact intermediate results, the1453two ultimate results will be mathematically equivalent. This is1454generally not true of computations involving inexact numbers since1455approximate methods such as floating point arithmetic may be used, but1456it is the duty of each implementation to make the result as close as1457practical to the mathematically ideal result.14581459Rational operations such as + should always produce exact results when1460given exact arguments. If the operation is unable to produce an exact1461result, then it may either report the violation of an implementation1462restriction or it may silently coerce its result to an inexact value.1463See [[#Implementation restrictions|the next section]].14641465With the exception of inexact->exact, the operations described in this1466section must generally return inexact results when given any inexact1467arguments. An operation may, however, return an exact result if it can1468prove that the value of the result is unaffected by the inexactness of1469its arguments. For example, multiplication of any number by an exact1470zero may produce an exact zero result, even if the other argument is1471inexact.14721473==== Implementation restrictions14741475Implementations of Scheme are not required to implement the whole1476tower of subtypes given under "[[#Numerical types|Numerical types]]",1477but they must implement a coherent subset consistent with both the1478purposes of the implementation and the spirit of the Scheme1479language. For example, an implementation in which all numbers are real1480may still be quite useful.14811482Implementations may also support only a limited range of numbers of any1483type, subject to the requirements of this section. The supported range1484for exact numbers of any type may be different from the supported range1485for inexact numbers of that type. For example, an implementation that1486uses flonums to represent all its inexact real numbers may support a1487practically unbounded range of exact integers and rationals while1488limiting the range of inexact reals (and therefore the range of inexact1489integers and rationals) to the dynamic range of the flonum format.1490Furthermore the gaps between the representable inexact integers and1491rationals are likely to be very large in such an implementation as the1492limits of this range are approached.14931494An implementation of Scheme must support exact integers throughout the1495range of numbers that may be used for indexes of lists, vectors, and1496strings or that may result from computing the length of a list, vector,1497or string. The length, vector-length, and string-length procedures must1498return an exact integer, and it is an error to use anything but an1499exact integer as an index. Furthermore any integer constant within the1500index range, if expressed by an exact integer syntax, will indeed be1501read as an exact integer, regardless of any implementation restrictions1502that may apply outside this range. Finally, the procedures listed below1503will always return an exact integer result provided all their arguments1504are exact integers and the mathematically expected result is1505representable as an exact integer within the implementation:15061507 + - *1508 quotient remainder modulo1509 max min abs1510 numerator denominator gcd1511 lcm floor ceiling1512 truncate round rationalize1513 expt15141515Implementations are encouraged, but not required, to support exact1516integers and exact rationals of practically unlimited size and1517precision, and to implement the above procedures and the / procedure in1518such a way that they always return exact results when given exact1519arguments. If one of these procedures is unable to deliver an exact1520result when given exact arguments, then it may either report a1521violation of an implementation restriction or it may silently coerce1522its result to an inexact number. Such a coercion may cause an error1523later.15241525An implementation may use floating point and other approximate1526representation strategies for inexact numbers. This report recommends,1527but does not require, that the IEEE 32-bit and 64-bit floating point1528standards be followed by implementations that use flonum1529representations, and that implementations using other representations1530should match or exceed the precision achievable using these floating1531point standards [12].15321533In particular, implementations that use flonum representations must1534follow these rules: A flonum result must be represented with at least1535as much precision as is used to express any of the inexact arguments to1536that operation. It is desirable (but not required) for potentially1537inexact operations such as sqrt, when applied to exact arguments, to1538produce exact answers whenever possible (for example the square root of1539an exact 4 ought to be an exact 2). If, however, an exact number is1540operated upon so as to produce an inexact result (as by sqrt), and if1541the result is represented as a flonum, then the most precise flonum1542format available must be used; but if the result is represented in some1543other way then the representation must have at least as much precision1544as the most precise flonum format available.15451546Although Scheme allows a variety of written notations for numbers, any1547particular implementation may support only some of them. For example,1548an implementation in which all numbers are real need not support the1549rectangular and polar notations for complex numbers. If an1550implementation encounters an exact numerical constant that it cannot1551represent as an exact number, then it may either report a violation of1552an implementation restriction or it may silently represent the constant1553by an inexact number.15541555==== Syntax of numerical constants15561557For a complete formal description of the syntax of the written1558representations for numbers, see the R5RS report. Note that case is1559not significant in numerical constants.15601561A number may be written in binary, octal, decimal, or hexadecimal by1562the use of a radix prefix. The radix prefixes are #b (binary), #o1563(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a1564number is assumed to be expressed in decimal.15651566A numerical constant may be specified to be either exact or inexact by1567a prefix. The prefixes are #e for exact, and #i for inexact. An1568exactness prefix may appear before or after any radix prefix that is1569used. If the written representation of a number has no exactness1570prefix, the constant may be either inexact or exact. It is inexact if1571it contains a decimal point, an exponent, or a "#" character in the1572place of a digit, otherwise it is exact. In systems with inexact1573numbers of varying precisions it may be useful to specify the precision1574of a constant. For this purpose, numerical constants may be written1575with an exponent marker that indicates the desired precision of the1576inexact representation. The letters s, f, d, and l specify the use of1577short, single, double, and long precision, respectively. (When fewer1578than four internal inexact representations exist, the four size1579specifications are mapped onto those available. For example, an1580implementation with two internal representations may map short and1581single together and long and double together.) In addition, the1582exponent marker e specifies the default precision for the1583implementation. The default precision has at least as much precision as1584double, but implementations may wish to allow this default to be set by1585the user.15861587 3.14159265358979F01588 Round to single --- 3.1415931589 0.6L01590 Extend to long --- .60000000000000015911592==== Numerical operations15931594The numerical routines described below have argument restrictions,1595which are encoded in the naming conventions of the arguments as1596given in the procedure's signature. The conventions are as follows:15971598; {{obj}} : any object1599; {{list, list1, ... listj, ... list : (see "[[#Pairs_and_lists|Pairs and lists]]" below)1600; {{z, z1, ... zj, ...}} : complex number1601; {{x, x1, ... xj, ...}} : real number1602; {{y, y1, ... yj, ...}} : real number1603; {{q, q1, ... qj, ...}} : rational number1604; {{n, n1, ... nj, ...}} : integer1605; {{k, k1, ... kj, ...}} : exact non-negative integer16061607The examples used in this section assume that any1608numerical constant written using an exact notation is indeed1609represented as an exact number. Some examples also assume that certain1610numerical constants written using an inexact notation can be1611represented without loss of accuracy; the inexact constants were chosen1612so that this is likely to be true in implementations that use flonums1613to represent inexact numbers.16141615<procedure>(number? obj)</procedure><br>1616<procedure>(complex? obj)</procedure><br>1617<procedure>(real? obj)</procedure><br>1618<procedure>(rational? obj)</procedure><br>1619<procedure>(integer? obj)</procedure><br>16201621These numerical type predicates can be applied to any kind of argument,1622including non-numbers. They return #t if the object is of the named1623type, and otherwise they return #f. In general, if a type predicate is1624true of a number then all higher type predicates are also true of that1625number. Consequently, if a type predicate is false of a number, then1626all lower type predicates are also false of that number. If z is an1627inexact complex number, then (real? z) is true if and only if (zero?1628(imag-part z)) is true. If x is an inexact real number, then (integer?1629x) is true if and only if (= x (round x)).16301631 (complex? 3+4i) ===> #t1632 (complex? 3) ===> #t1633 (real? 3) ===> #t1634 (real? -2.5+0.0i) ===> #t1635 (real? #e1e10) ===> #t1636 (rational? 6/10) ===> #t1637 (rational? 6/3) ===> #t1638 (integer? 3+0i) ===> #t1639 (integer? 3.0) ===> #t1640 (integer? 8/4) ===> #t16411642Note: The behavior of these type predicates on inexact numbers is1643unreliable, since any inaccuracy may affect the result.16441645Note: In many implementations the rational? procedure will be the1646same as real?, and the complex? procedure will be the same as1647number?, but unusual implementations may be able to represent some1648irrational numbers exactly or may extend the number system to1649support some kind of non-complex numbers.16501651<procedure>(exact? z)</procedure><br>1652<procedure>(inexact? z)</procedure><br>16531654These numerical predicates provide tests for the exactness of a1655quantity. For any Scheme number, precisely one of these predicates is1656true.16571658<procedure>(= z[1] z[2] z[3] ...)</procedure><br>1659<procedure>(< x[1] x[2] x[3] ...)</procedure><br>1660<procedure>(> x[1] x[2] x[3] ...)</procedure><br>1661<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>1662<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>16631664These procedures return #t if their arguments are (respectively):1665equal, monotonically increasing, monotonically decreasing,1666monotonically nondecreasing, or monotonically nonincreasing.16671668These predicates are required to be transitive.16691670Note: The traditional implementations of these predicates in1671Lisp-like languages are not transitive.16721673Note: While it is not an error to compare inexact numbers using1674these predicates, the results may be unreliable because a small1675inaccuracy may affect the result; this is especially true of = and1676zero?. When in doubt, consult a numerical analyst.16771678<procedure>(zero? z)</procedure><br>1679<procedure>(positive? x)</procedure><br>1680<procedure>(negative? x)</procedure><br>1681<procedure>(odd? n)</procedure><br>1682<procedure>(even? n)</procedure><br>16831684These numerical predicates test a number for a particular property,1685returning #t or #f. See note above.16861687<procedure>(max x[1] x[2] ...)</procedure><br>1688<procedure>(min x[1] x[2] ...)</procedure><br>16891690These procedures return the maximum or minimum of their arguments.16911692 (max 3 4) ===> 4 ; exact1693 (max 3.9 4) ===> 4.0 ; inexact16941695Note: If any argument is inexact, then the result will also be1696inexact (unless the procedure can prove that the inaccuracy is not1697large enough to affect the result, which is possible only in1698unusual implementations). If min or max is used to compare numbers1699of mixed exactness, and the numerical value of the result cannot be1700represented as an inexact number without loss of accuracy, then the1701procedure may report a violation of an implementation restriction.17021703<procedure>(+ z[1] ...)</procedure><br>1704<procedure>(* z[1] ...)</procedure><br>17051706These procedures return the sum or product of their arguments.17071708 (+ 3 4) ===> 71709 (+ 3) ===> 31710 (+) ===> 01711 (* 4) ===> 41712 (*) ===> 117131714<procedure>(- z[1] z[2])</procedure><br>1715<procedure>(- z)</procedure><br>1716<procedure>(- z[1] z[2] ...)</procedure><br>1717<procedure>(/ z[1] z[2])</procedure><br>1718<procedure>(/ z)</procedure><br>1719<procedure>(/ z[1] z[2] ...)</procedure><br>17201721With two or more arguments, these procedures return the difference or1722quotient of their arguments, associating to the left. With one1723argument, however, they return the additive or multiplicative inverse1724of their argument.17251726 (- 3 4) ===> -11727 (- 3 4 5) ===> -61728 (- 3) ===> -31729 (/ 3 4 5) ===> 3/201730 (/ 3) ===> 1/317311732<procedure>(abs x)</procedure><br>17331734Abs returns the absolute value of its argument.17351736 (abs -7) ===> 717371738<procedure>(quotient n[1] n[2])</procedure><br>1739<procedure>(remainder n[1] n[2])</procedure><br>1740<procedure>(modulo n[1] n[2])</procedure><br>17411742These procedures implement number-theoretic (integer) division. n[2]1743should be non-zero. All three procedures return integers. If n[1]/n[2]1744is an integer:17451746 (quotient n[1] n[2]) ===> n[1]/n[2]1747 (remainder n[1] n[2]) ===> 01748 (modulo n[1] n[2]) ===> 017491750If n[1]/n[2] is not an integer:17511752 (quotient n[1] n[2]) ===> n[q]1753 (remainder n[1] n[2]) ===> n[r]1754 (modulo n[1] n[2]) ===> n[m]17551756where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <1757|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],1758n[r] has the same sign as n[1], and n[m] has the same sign as n[2].17591760From this we can conclude that for integers n[1] and n[2] with n[2] not1761equal to 0,17621763 (= n[1] (+ (* n[2] (quotient n[1] n[2]))1764 (remainder n[1] n[2])))1765 ===> #t17661767provided all numbers involved in that computation are exact.17681769 (modulo 13 4) ===> 11770 (remainder 13 4) ===> 117711772 (modulo -13 4) ===> 31773 (remainder -13 4) ===> -117741775 (modulo 13 -4) ===> -31776 (remainder 13 -4) ===> 117771778 (modulo -13 -4) ===> -11779 (remainder -13 -4) ===> -117801781 (remainder -13 -4.0) ===> -1.0 ; inexact17821783<procedure>(gcd n[1] ...)</procedure><br>1784<procedure>(lcm n[1] ...)</procedure><br>17851786These procedures return the greatest common divisor or least common1787multiple of their arguments. The result is always non-negative.17881789 (gcd 32 -36) ===> 41790 (gcd) ===> 01791 (lcm 32 -36) ===> 2881792 (lcm 32.0 -36) ===> 288.0 ; inexact1793 (lcm) ===> 117941795<procedure>(numerator q)</procedure><br>1796<procedure>(denominator q)</procedure><br>17971798These procedures return the numerator or denominator of their argument;1799the result is computed as if the argument was represented as a fraction1800in lowest terms. The denominator is always positive. The denominator of18010 is defined to be 1.18021803 (numerator (/ 6 4)) ===> 31804 (denominator (/ 6 4)) ===> 21805 (denominator1806 (exact->inexact (/ 6 4))) ===> 2.018071808<procedure>(floor x)</procedure><br>1809<procedure>(ceiling x)</procedure><br>1810<procedure>(truncate x)</procedure><br>1811<procedure>(round x)</procedure><br>18121813These procedures return integers. Floor returns the largest integer not1814larger than x. Ceiling returns the smallest integer not smaller than x.1815Truncate returns the integer closest to x whose absolute value is not1816larger than the absolute value of x. Round returns the closest integer1817to x, rounding to even when x is halfway between two integers.18181819Rationale: Round rounds to even for consistency with the default1820rounding mode specified by the IEEE floating point standard.18211822Note: If the argument to one of these procedures is inexact, then1823the result will also be inexact. If an exact value is needed, the1824result should be passed to the inexact->exact procedure.18251826 (floor -4.3) ===> -5.01827 (ceiling -4.3) ===> -4.01828 (truncate -4.3) ===> -4.01829 (round -4.3) ===> -4.018301831 (floor 3.5) ===> 3.01832 (ceiling 3.5) ===> 4.01833 (truncate 3.5) ===> 3.01834 (round 3.5) ===> 4.0 ; inexact18351836 (round 7/2) ===> 4 ; exact1837 (round 7) ===> 718381839<procedure>(rationalize x y)</procedure><br>18401841Rationalize returns the simplest rational number differing from x by no1842more than y. A rational number r[1] is simpler than another rational1843number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)1844and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.1845Although not all rationals are comparable in this ordering (consider 2/18467 and 3/5) any interval contains a rational number that is simpler than1847every other rational number in that interval (the simpler 2/5 lies1848between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of1849all.18501851 (rationalize1852 (inexact->exact .3) 1/10) ===> 1/3 ; exact1853 (rationalize .3 1/10) ===> #i1/3 ; inexact18541855<procedure>(exp z)</procedure><br>1856<procedure>(log z)</procedure><br>1857<procedure>(sin z)</procedure><br>1858<procedure>(cos z)</procedure><br>1859<procedure>(tan z)</procedure><br>1860<procedure>(asin z)</procedure><br>1861<procedure>(acos z)</procedure><br>1862<procedure>(atan z)</procedure><br>1863<procedure>(atan y x)</procedure><br>18641865These procedures are part of every implementation that supports general1866real numbers; they compute the usual transcendental functions. Log1867computes the natural logarithm of z (not the base ten logarithm). Asin,1868acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and1869arctangent (tan^-1), respectively. The two-argument variant of atan1870computes (angle (make-rectangular x y)) (see below), even in1871implementations that don't support general complex numbers.18721873In general, the mathematical functions log, arcsine, arccosine, and1874arctangent are multiply defined. The value of log z is defined to be1875the one whose imaginary part lies in the range from -pi1876(exclusive) to pi (inclusive). log 0 is undefined. With log1877defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are1878according to the following formulae:18791880 sin^-1 z = - i log (i z + (1 - z^2)^1/2)18811882 cos^-1 z = pi / 2 - sin^-1 z18831884 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)18851886The above specification follows [27], which in turn cites [19]; refer1887to these sources for more detailed discussion of branch cuts, boundary1888conditions, and implementation of these functions. When it is possible1889these procedures produce a real result from a real argument.18901891<procedure>(sqrt z)</procedure><br>18921893Returns the principal square root of z. The result will have either1894positive real part, or zero real part and non-negative imaginary part.18951896<procedure>(expt z[1] z[2])</procedure><br>18971898Returns z[1] raised to the power z[2]. For z[1] != 018991900 z[1]^z[2] = e^z[2] log z[1]190119020^z is 1 if z = 0 and 0 otherwise.19031904<procedure>(make-rectangular x[1] x[2])</procedure><br>1905<procedure>(make-polar x[3] x[4])</procedure><br>1906<procedure>(real-part z)</procedure><br>1907<procedure>(imag-part z)</procedure><br>1908<procedure>(magnitude z)</procedure><br>1909<procedure>(angle z)</procedure><br>19101911These procedures are part of every implementation that supports general1912complex numbers. Suppose x[1], x[2], x[3], and x[4] are real numbers1913and z is a complex number such that19141915 z = x[1] + x[2]i = x[3] . e^i x[4]19161917Then19181919 (make-rectangular x[1] x[2]) ===> z1920 (make-polar x[3] x[4]) ===> z1921 (real-part z) ===> x[1]1922 (imag-part z) ===> x[2]1923 (magnitude z) ===> |x[3]|1924 (angle z) ===> x[angle]19251926where - pi < x[angle] < pi with x[angle] = x[4] + 2 pi n1927for some integer n.19281929Rationale: Magnitude is the same as abs for a real argument, but1930abs must be present in all implementations, whereas magnitude need1931only be present in implementations that support general complex1932numbers.19331934<procedure>(exact->inexact z)</procedure><br>1935<procedure>(inexact->exact z)</procedure><br>19361937Exact->inexact returns an inexact representation of z. The value1938returned is the inexact number that is numerically closest to the1939argument. If an exact argument has no reasonably close inexact1940equivalent, then a violation of an implementation restriction may be1941reported.19421943Inexact->exact returns an exact representation of z. The value returned1944is the exact number that is numerically closest to the argument. If an1945inexact argument has no reasonably close exact equivalent, then a1946violation of an implementation restriction may be reported.19471948These procedures implement the natural one-to-one correspondence1949between exact and inexact integers throughout an1950implementation-dependent range.1951See "[[#implementation-restrictions|Implementation restrictions]]".19521953==== Numerical input and output19541955<procedure>(number->string z [radix])</procedure>19561957Radix must be an exact integer. The R5RS standard only requires1958implementations to support 2, 8, 10, or 16, but CHICKEN allows any1959radix between 2 and 36, inclusive (note: a bug in CHICKEN 5 currently1960limits the upper bound to 16). If omitted, radix defaults to196110. The procedure number->string takes a number and a radix and1962returns as a string an external representation of the given number in1963the given radix such that19641965 (let ((number number)1966 (radix radix))1967 (eqv? number1968 (string->number (number->string number1969 radix)1970 radix)))19711972is true. It is an error if no possible result makes this expression1973true.19741975If z is inexact, the radix is 10, and the above expression can be1976satisfied by a result that contains a decimal point, then the result1977contains a decimal point and is expressed using the minimum number of1978digits (exclusive of exponent and trailing zeroes) needed to make the1979above expression true [3, 5]; otherwise the format of the result is1980unspecified.19811982The result returned by number->string never contains an explicit radix1983prefix.19841985Note: The error case can occur only when z is not a complex1986number or is a complex number with a non-rational real or imaginary1987part.19881989Rationale: If z is an inexact number represented using flonums,1990and the radix is 10, then the above expression is normally1991satisfied by a result containing a decimal point. The unspecified1992case allows for infinities, NaNs, and non-flonum representations.19931994As an extension to R5RS, CHICKEN supports reading and writing the1995special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',1996as well as negative zero.19971998<procedure>(string->number string)</procedure><br>1999<procedure>(string->number string radix)</procedure><br>20002001Returns a number of the maximally precise representation expressed by2002the given string. Radix must be an exact integer. The R5RS standard2003only requires implementations to support 2, 8, 10, or 16, but CHICKEN2004allows any radix between 2 and 36, inclusive. If supplied, radix is a2005default radix that may be overridden by an explicit radix prefix in2006string (e.g. "#o177"). If radix is not supplied, then the default2007radix is 10. If string is not a syntactically valid notation for a2008number, then string->number returns #f.20092010 (string->number "100") ===> 1002011 (string->number "100" 16) ===> 2562012 (string->number "1e2") ===> 100.02013 (string->number "15##") ===> 1500.020142015Note: The domain of string->number may be restricted by2016implementations in the following ways. String->number is permitted2017to return #f whenever string contains an explicit radix prefix. If2018all numbers supported by an implementation are real, then string->2019number is permitted to return #f whenever string uses the polar or2020rectangular notations for complex numbers. If all numbers are2021integers, then string->number may return #f whenever the fractional2022notation is used. If all numbers are exact, then string->number may2023return #f whenever an exponent marker or explicit exactness prefix2024is used, or if a # appears in place of a digit. If all inexact2025numbers are integers, then string->number may return #f whenever a2026decimal point is used.20272028As an extension to R5RS, CHICKEN supports reading and writing the2029special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',2030as well as negative zero.20312032=== Other data types20332034This section describes operations on some of Scheme's non-numeric data2035types: booleans, pairs, lists, symbols, characters, strings and2036vectors.20372038==== Booleans20392040The standard boolean objects for true and false are written as #t and #f.2041What really matters, though, are the objects that the Scheme2042conditional expressions (if, cond, and, or, do) treat as true or false.2043The phrase "a true value" (or sometimes just "true") means any2044object treated as true by the conditional expressions, and the phrase2045"a false value" (or "false") means any object treated as false by2046the conditional expressions.20472048Of all the standard Scheme values, only #f counts as false in2049conditional expressions. Except for #f, all standard Scheme values,2050including #t, pairs, the empty list, symbols, numbers, strings,2051vectors, and procedures, count as true.20522053Note: Programmers accustomed to other dialects of Lisp should be2054aware that Scheme distinguishes both #f and the empty list from the2055symbol nil.20562057Boolean constants evaluate to themselves, so they do not need to be2058quoted in programs.20592060 #t ===> #t2061 #f ===> #f2062 '#f ===> #f20632064<procedure>(not obj)</procedure><br>20652066Not returns #t if obj is false, and returns #f otherwise.20672068 (not #t) ===> #f2069 (not 3) ===> #f2070 (not (list 3)) ===> #f2071 (not #f) ===> #t2072 (not '()) ===> #f2073 (not (list)) ===> #f2074 (not 'nil) ===> #f20752076<procedure>(boolean? obj)</procedure><br>20772078Boolean? returns #t if obj is either #t or #f and returns #f otherwise.20792080 (boolean? #f) ===> #t2081 (boolean? 0) ===> #f2082 (boolean? '()) ===> #f20832084==== Pairs and lists20852086A pair (sometimes called a dotted pair) is a record structure with two2087fields called the car and cdr fields (for historical reasons). Pairs2088are created by the procedure cons. The car and cdr fields are accessed2089by the procedures car and cdr. The car and cdr fields are assigned by2090the procedures set-car! and set-cdr!.20912092Pairs are used primarily to represent lists. A list can be defined2093recursively as either the empty list or a pair whose cdr is a list.2094More precisely, the set of lists is defined as the smallest set X such2095that20962097* The empty list is in X.2098* If list is in X, then any pair whose cdr field contains list is2099 also in X.21002101The objects in the car fields of successive pairs of a list are the2102elements of the list. For example, a two-element list is a pair whose2103car is the first element and whose cdr is a pair whose car is the2104second element and whose cdr is the empty list. The length of a list is2105the number of elements, which is the same as the number of pairs.21062107The empty list is a special object of its own type (it is not a pair);2108it has no elements and its length is zero.21092110Note: The above definitions imply that all lists have finite2111length and are terminated by the empty list.21122113The most general notation (external representation) for Scheme pairs is2114the "dotted" notation (c[1] . c[2]) where c[1] is the value of the2115car field and c[2] is the value of the cdr field. For example (4 . 5)2116is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the2117external representation of a pair, not an expression that evaluates to2118a pair.21192120A more streamlined notation can be used for lists: the elements of the2121list are simply enclosed in parentheses and separated by spaces. The2122empty list is written () . For example,21232124 (a b c d e)21252126and21272128 (a . (b . (c . (d . (e . ())))))21292130are equivalent notations for a list of symbols.21312132A chain of pairs not ending in the empty list is called an improper2133list. Note that an improper list is not a list. The list and dotted2134notations can be combined to represent improper lists:21352136 (a b c . d)21372138is equivalent to21392140 (a . (b . (c . d)))21412142Whether a given pair is a list depends upon what is stored in the cdr2143field. When the set-cdr! procedure is used, an object can be a list one2144moment and not the next:21452146 (define x (list 'a 'b 'c))2147 (define y x)2148 y ===> (a b c)2149 (list? y) ===> #t2150 (set-cdr! x 4) ===> unspecified2151 x ===> (a . 4)2152 (eqv? x y) ===> #t2153 y ===> (a . 4)2154 (list? y) ===> #f2155 (set-cdr! x x) ===> unspecified2156 (list? x) ===> #f21572158Within literal expressions and representations of objects read by the2159read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>2160denote two-element lists whose first elements are the symbols quote,2161quasiquote, unquote, and unquote-splicing, respectively. The second2162element in each case is <datum>. This convention is supported so that2163arbitrary Scheme programs may be represented as lists. That is,2164according to Scheme's grammar, every <expression> is also a <datum>.2165Among other things, this permits the use of the read procedure to2166parse Scheme programs.21672168<procedure>(pair? obj)</procedure><br>21692170Pair? returns #t if obj is a pair, and otherwise returns #f.2171NOTE: [[Module (chicken base)#weak-pairs|Weak pairs]] are regarded2172as pairs by this procedure.21732174 (pair? '(a . b)) ===> #t2175 (pair? '(a b c)) ===> #t2176 (pair? '()) ===> #f2177 (pair? '#(a b)) ===> #f2178 (pair? (cons 1 2)) ===> #t21792180 (import (chicken base))2181 (pair? (weak-cons 1 2)) ===> #t21822183<procedure>(cons obj[1] obj[2])</procedure><br>21842185Returns a newly allocated pair whose car is obj[1] and whose cdr is2186obj[2]. The pair is guaranteed to be different (in the sense of eqv?)2187from every existing object.21882189 (cons 'a '()) ===> (a)2190 (cons '(a) '(b c d)) ===> ((a) b c d)2191 (cons "a" '(b c)) ===> ("a" b c)2192 (cons 'a 3) ===> (a . 3)2193 (cons '(a b) 'c) ===> ((a b) . c)21942195<procedure>(car pair)</procedure><br>21962197Returns the contents of the car field of pair. Note that it is an error2198to take the car of the empty list.21992200 (car '(a b c)) ===> a2201 (car '((a) b c d)) ===> (a)2202 (car '(1 . 2)) ===> 12203 (car '()) ===> error2204 (car (cons 1 2)) ===> 122052206 (import (chicken base))2207 (car (weak-cons 1 2)) ===> 122082209<procedure>(cdr pair)</procedure><br>22102211Returns the contents of the cdr field of pair. Note that it is an error2212to take the cdr of the empty list.22132214 (cdr '((a) b c d)) ===> (b c d)2215 (cdr '(1 . 2)) ===> 22216 (cdr '()) ===> error2217 (cdr (cons 1 2)) ===> 222182219 (import (chicken base))2220 (cdr (weak-cons 1 2)) ===> 222212222<procedure>(set-car! pair obj)</procedure><br>22232224Stores obj in the car field of pair. The value returned by set-car! is2225unspecified.22262227 (define (f) (list 'not-a-constant-list))2228 (define (g) '(constant-list))2229 (set-car! (f) 3) ===> unspecified2230 (set-car! (g) 3) ===> error22312232<procedure>(set-cdr! pair obj)</procedure><br>22332234Stores obj in the cdr field of pair. The value returned by set-cdr! is2235unspecified.22362237<procedure>(caar pair)</procedure><br>2238<procedure>(cadr pair)</procedure><br>2239<procedure>(cdar pair)</procedure><br>2240<procedure>(cddr pair)</procedure><br>2241<procedure>(caaar pair)</procedure><br>2242<procedure>(caadr pair)</procedure><br>2243<procedure>(cadar pair)</procedure><br>2244<procedure>(caddr pair)</procedure><br>2245<procedure>(cdaar pair)</procedure><br>2246<procedure>(cdadr pair)</procedure><br>2247<procedure>(cddar pair)</procedure><br>2248<procedure>(cdddr pair)</procedure><br>2249<procedure>(caaaar pair)</procedure><br>2250<procedure>(caaadr pair)</procedure><br>2251<procedure>(caadar pair)</procedure><br>2252<procedure>(caaddr pair)</procedure><br>2253<procedure>(cadaar pair)</procedure><br>2254<procedure>(cadadr pair)</procedure><br>2255<procedure>(caddar pair)</procedure><br>2256<procedure>(cadddr pair)</procedure><br>2257<procedure>(cdaaar pair)</procedure><br>2258<procedure>(cdaadr pair)</procedure><br>2259<procedure>(cdadar pair)</procedure><br>2260<procedure>(cdaddr pair)</procedure><br>2261<procedure>(cddaar pair)</procedure><br>2262<procedure>(cddadr pair)</procedure><br>2263<procedure>(cdddar pair)</procedure><br>2264<procedure>(cddddr pair)</procedure><br>22652266These procedures are compositions of car and cdr, where for example2267caddr could be defined by22682269 (define caddr (lambda (x) (car (cdr (cdr x))))).22702271<procedure>(null? obj)</procedure><br>22722273Returns #t if obj is the empty list, otherwise returns #f.22742275<procedure>(list? obj)</procedure><br>22762277Returns #t if obj is a list, otherwise returns #f. By definition, all2278lists have finite length and are terminated by the empty list.22792280 (list? '(a b c)) ===> #t2281 (list? '()) ===> #t2282 (list? '(a . b)) ===> #f2283 (let ((x (list 'a)))2284 (set-cdr! x x)2285 (list? x)) ===> #f22862287<procedure>(list obj ...)</procedure><br>22882289Returns a newly allocated list of its arguments.22902291 (list 'a (+ 3 4) 'c) ===> (a 7 c)2292 (list) ===> ()22932294<procedure>(length list)</procedure><br>22952296Returns the length of list.22972298 (length '(a b c)) ===> 32299 (length '(a (b) (c d e))) ===> 32300 (length '()) ===> 023012302<procedure>(append list ...)</procedure><br>23032304Returns a list consisting of the elements of the first list followed by2305the elements of the other lists.23062307 (append '(x) '(y)) ===> (x y)2308 (append '(a) '(b c d)) ===> (a b c d)2309 (append '(a (b)) '((c))) ===> (a (b) (c))23102311The resulting list is always newly allocated, except that it shares2312structure with the last list argument. The last argument may actually2313be any object; an improper list results if the last argument is not a2314proper list.23152316 (append '(a b) '(c . d)) ===> (a b c . d)2317 (append '() 'a) ===> a23182319<procedure>(reverse list)</procedure><br>23202321Returns a newly allocated list consisting of the elements of list in2322reverse order.23232324 (reverse '(a b c)) ===> (c b a)2325 (reverse '(a (b c) d (e (f))))2326 ===> ((e (f)) d (b c) a)23272328<procedure>(list-tail list k)</procedure><br>23292330Returns the sublist of list obtained by omitting the first k elements.2331It is an error if list has fewer than k elements. List-tail could be2332defined by23332334 (define list-tail2335 (lambda (x k)2336 (if (zero? k)2337 x2338 (list-tail (cdr x) (- k 1)))))23392340<procedure>(list-ref list k)</procedure><br>23412342Returns the kth element of list. (This is the same as the car of2343(list-tail list k).) It is an error if list has fewer than k elements.23442345 (list-ref '(a b c d) 2) ===> c2346 (list-ref '(a b c d)2347 (inexact->exact (round 1.8)))2348 ===> c23492350<procedure>(memq obj list)</procedure><br>2351<procedure>(memv obj list)</procedure><br>2352<procedure>(member obj list)</procedure><br>23532354These procedures return the first sublist of list whose car is obj,2355where the sublists of list are the non-empty lists returned by2356(list-tail list k) for k less than the length of list. If obj does not2357occur in list, then #f (not the empty list) is returned. Memq uses eq?2358to compare obj with the elements of list, while memv uses eqv? and2359member uses equal?.23602361 (memq 'a '(a b c)) ===> (a b c)2362 (memq 'b '(a b c)) ===> (b c)2363 (memq 'a '(b c d)) ===> #f2364 (memq (list 'a) '(b (a) c)) ===> #f2365 (member (list 'a)2366 '(b (a) c)) ===> ((a) c)2367 (memq 101 '(100 101 102)) ===> unspecified2368 (memv 101 '(100 101 102)) ===> (101 102)23692370<procedure>(assq obj alist)</procedure><br>2371<procedure>(assv obj alist)</procedure><br>2372<procedure>(assoc obj alist)</procedure><br>23732374Alist (for "association list") must be a list of pairs. These2375procedures find the first pair in alist whose car field is obj, and2376returns that pair. If no pair in alist has obj as its car, then #f (not2377the empty list) is returned. Assq uses eq? to compare obj with the car2378fields of the pairs in alist, while assv uses eqv? and assoc uses2379equal?.23802381 (define e '((a 1) (b 2) (c 3)))2382 (assq 'a e) ===> (a 1)2383 (assq 'b e) ===> (b 2)2384 (assq 'd e) ===> #f2385 (assq (list 'a) '(((a)) ((b)) ((c))))2386 ===> #f2387 (assoc (list 'a) '(((a)) ((b)) ((c))))2388 ===> ((a))2389 (assq 5 '((2 3) (5 7) (11 13)))2390 ===> unspecified2391 (assv 5 '((2 3) (5 7) (11 13)))2392 ===> (5 7)23932394Rationale: Although they are ordinarily used as predicates, memq,2395memv, member, assq, assv, and assoc do not have question marks in2396their names because they return useful values rather than just #t2397or #f.23982399==== Symbols24002401Symbols are objects whose usefulness rests on the fact that two symbols2402are identical (in the sense of eqv?) if and only if their names are2403spelled the same way. This is exactly the property needed to represent2404identifiers in programs, and so most implementations of Scheme use them2405internally for that purpose. Symbols are useful for many other2406applications; for instance, they may be used the way enumerated values2407are used in Pascal.24082409The rules for writing a symbol are exactly the same as the rules for2410writing an identifier.24112412It is guaranteed that any symbol that has been returned as part of a2413literal expression, or read using the read procedure, and subsequently2414written out using the write procedure, will read back in as the2415identical symbol (in the sense of eqv?). The string->symbol procedure,2416however, can create symbols for which this write/read invariance may2417not hold because their names contain special characters or letters in2418the non-standard case.24192420Note: Some implementations of Scheme have a feature known as2421"slashification" in order to guarantee write/read invariance for2422all symbols, but historically the most important use of this2423feature has been to compensate for the lack of a string data type.24242425Some implementations also have "uninterned symbols", which defeat2426write/read invariance even in implementations with slashification,2427and also generate exceptions to the rule that two symbols are the2428same if and only if their names are spelled the same.24292430<procedure>(symbol? obj)</procedure><br>24312432Returns #t if obj is a symbol, otherwise returns #f.24332434 (symbol? 'foo) ===> #t2435 (symbol? (car '(a b))) ===> #t2436 (symbol? "bar") ===> #f2437 (symbol? 'nil) ===> #t2438 (symbol? '()) ===> #f2439 (symbol? #f) ===> #f24402441<procedure>(symbol->string symbol)</procedure><br>24422443Returns the name of symbol as a string. If the symbol was part of an2444object returned as the value of a literal expression (see2445"[[#literal-expressions|literal expressions]]") or by a call to the2446read procedure, and its name contains alphabetic characters, then the2447string returned will contain characters in the implementation's2448preferred standard case -- some implementations will prefer upper2449case, others lower case. If the symbol was returned by string->symbol,2450the case of characters in the string returned will be the same as the2451case in the string that was passed to string->symbol. It is an error2452to apply mutation procedures like string-set! to strings returned by2453this procedure.24542455The following examples assume that the implementation's standard case2456is lower case:24572458 (symbol->string 'flying-fish)2459 ===> "flying-fish"2460 (symbol->string 'Martin) ===> "martin"2461 (symbol->string2462 (string->symbol "Malvina"))2463 ===> "Malvina"24642465<procedure>(string->symbol string)</procedure><br>24662467Returns the symbol whose name is string. This procedure can create2468symbols with names containing special characters or letters in the2469non-standard case, but it is usually a bad idea to create such symbols2470because in some implementations of Scheme they cannot be read as2471themselves. See symbol->string.24722473The following examples assume that the implementation's standard case2474is lower case:24752476 (eq? 'mISSISSIppi 'mississippi)2477 ===> #t2478 (string->symbol "mISSISSIppi")2479 ===> the symbol with name "mISSISSIppi"2480 (eq? 'bitBlt (string->symbol "bitBlt"))2481 ===> #f2482 (eq? 'JollyWog2483 (string->symbol2484 (symbol->string 'JollyWog)))2485 ===> #t2486 (string=? "K. Harper, M.D."2487 (symbol->string2488 (string->symbol "K. Harper, M.D.")))2489 ===> #t24902491==== Characters24922493Characters are objects that represent printed characters such as2494letters and digits. Characters are written using the notation #\2495<character> or #\<character name>. For example:24962497 #\a ; lower case letter2498 #\A ; upper case letter2499 #\( ; left parenthesis2500 #\ ; the space character2501 #\space ; the preferred way to write a space2502 #\newline ; the newline character25032504Case is significant in #\<character>, but not in #\<character name>. If2505<character> in #\<character> is alphabetic, then the character2506following <character> must be a delimiter character such as a space or2507parenthesis. This rule resolves the ambiguous case where, for example,2508the sequence of characters "#\space" could be taken to be either a2509representation of the space character or a representation of the2510character "#\s" followed by a representation of the symbol "pace."25112512Characters written in the #\ notation are self-evaluating. That is,2513they do not have to be quoted in programs. Some of the procedures that2514operate on characters ignore the difference between upper case and2515lower case. The procedures that ignore case have "-ci" (for "case2516insensitive") embedded in their names.25172518<procedure>(char? obj)</procedure><br>25192520Returns #t if obj is a character, otherwise returns #f.25212522<procedure>(char=? char[1] char[2])</procedure><br>2523<procedure>(char<? char[1] char[2])</procedure><br>2524<procedure>(char>? char[1] char[2])</procedure><br>2525<procedure>(char<=? char[1] char[2])</procedure><br>2526<procedure>(char>=? char[1] char[2])</procedure><br>25272528These procedures impose a total ordering on the set of characters. It2529is guaranteed that under this ordering:25302531* The upper case characters are in order. For example, (char<? #\A #\2532 B) returns #t.2533* The lower case characters are in order. For example, (char<? #\a #\2534 b) returns #t.2535* The digits are in order. For example, (char<? #\0 #\9) returns #t.2536* Either all the digits precede all the upper case letters, or vice2537 versa.2538* Either all the digits precede all the lower case letters, or vice2539 versa.25402541Some implementations may generalize these procedures to take more than2542two arguments, as with the corresponding numerical predicates.25432544<procedure>(char-ci=? char[1] char[2])</procedure><br>2545<procedure>(char-ci<? char[1] char[2])</procedure><br>2546<procedure>(char-ci>? char[1] char[2])</procedure><br>2547<procedure>(char-ci<=? char[1] char[2])</procedure><br>2548<procedure>(char-ci>=? char[1] char[2])</procedure><br>25492550These procedures are similar to char=? et cetera, but they treat upper2551case and lower case letters as the same. For example, (char-ci=? #\A #\2552a) returns #t. Some implementations may generalize these procedures to2553take more than two arguments, as with the corresponding numerical2554predicates.25552556<procedure>(char-alphabetic? char)</procedure><br>2557<procedure>(char-numeric? char)</procedure><br>2558<procedure>(char-whitespace? char)</procedure><br>2559<procedure>(char-upper-case? letter)</procedure><br>2560<procedure>(char-lower-case? letter)</procedure><br>25612562These procedures return #t if their arguments are alphabetic, numeric,2563whitespace, upper case, or lower case characters, respectively,2564otherwise they return #f. The following remarks, which are specific to2565the ASCII character set, are intended only as a guide: The alphabetic2566characters are the 52 upper and lower case letters. The numeric2567characters are the ten decimal digits. The whitespace characters are2568space, tab, line feed, form feed, and carriage return.25692570<procedure>(char->integer char)</procedure><br>2571<procedure>(integer->char n)</procedure><br>25722573Given a character, char->integer returns an exact integer2574representation of the character. Given an exact integer that is the2575image of a character under char->integer, integer->char returns that2576character. These procedures implement order-preserving isomorphisms2577between the set of characters under the char<=? ordering and some2578subset of the integers under the <= ordering. That is, if25792580 (char<=? a b) ===> #t and (<= x y) ===> #t25812582and x and y are in the domain of integer->char, then25832584 (<= (char->integer a)2585 (char->integer b)) ===> #t25862587 (char<=? (integer->char x)2588 (integer->char y)) ===> #t25892590Note that {{integer->char}} does currently not detect2591a negative argument and will quietly convert {{-1}} to2592{{#x1ffff}} in CHICKEN.25932594<procedure>(char-upcase char)</procedure><br>2595<procedure>(char-downcase char)</procedure><br>25962597These procedures return a character char[2] such that (char-ci=? char2598char[2]). In addition, if char is alphabetic, then the result of2599char-upcase is upper case and the result of char-downcase is lower2600case.26012602==== Strings26032604Strings are sequences of characters. Strings are written as sequences2605of characters enclosed within doublequotes ("). A doublequote can be2606written inside a string only by escaping it with a backslash (\), as in26072608"The word \"recursion\" has many meanings."26092610A backslash can be written inside a string only by escaping it with2611another backslash. Scheme does not specify the effect of a backslash2612within a string that is not followed by a doublequote or backslash.26132614A string constant may continue from one line to the next, but the exact2615contents of such a string are unspecified. The length of a string is2616the number of characters that it contains. This number is an exact,2617non-negative integer that is fixed when the string is created. The2618valid indexes of a string are the exact non-negative integers less than2619the length of the string. The first character of a string has index 0,2620the second has index 1, and so on.26212622In phrases such as "the characters of string beginning with index2623start and ending with index end," it is understood that the index2624start is inclusive and the index end is exclusive. Thus if start and2625end are the same index, a null substring is referred to, and if start2626is zero and end is the length of string, then the entire string is2627referred to.26282629Some of the procedures that operate on strings ignore the difference2630between upper and lower case. The versions that ignore case have2631"-ci" (for "case insensitive") embedded in their names.26322633<procedure>(string? obj)</procedure><br>26342635Returns #t if obj is a string, otherwise returns #f.26362637<procedure>(make-string k)</procedure><br>2638<procedure>(make-string k char)</procedure><br>26392640Make-string returns a newly allocated string of length k. If char is2641given, then all elements of the string are initialized to char,2642otherwise the contents of the string are unspecified.26432644<procedure>(string char ...)</procedure><br>26452646Returns a newly allocated string composed of the arguments.26472648<procedure>(string-length string)</procedure><br>26492650Returns the number of characters in the given string.26512652<procedure>(string-ref string k)</procedure><br>26532654k must be a valid index of string. String-ref returns character k of2655string using zero-origin indexing.26562657<procedure>(string-set! string k char)</procedure><br>26582659k must be a valid index of string. String-set! stores char in element k2660of string and returns an unspecified value.26612662 (define (f) (make-string 3 #\*))2663 (define (g) "***")2664 (string-set! (f) 0 #\?) ===> unspecified2665 (string-set! (g) 0 #\?) ===> error2666 (string-set! (symbol->string 'immutable)2667 02668 #\?) ===> error26692670<procedure>(string=? string[1] string[2])</procedure><br>2671<procedure>(string-ci=? string[1] string[2])</procedure><br>26722673Returns #t if the two strings are the same length and contain the same2674characters in the same positions, otherwise returns #f. String-ci=?2675treats upper and lower case letters as though they were the same2676character, but string=? treats upper and lower case as distinct2677characters.26782679<procedure>(string<? string[1] string[2])</procedure><br>2680<procedure>(string>? string[1] string[2])</procedure><br>2681<procedure>(string<=? string[1] string[2])</procedure><br>2682<procedure>(string>=? string[1] string[2])</procedure><br>2683<procedure>(string-ci<? string[1] string[2])</procedure><br>2684<procedure>(string-ci>? string[1] string[2])</procedure><br>2685<procedure>(string-ci<=? string[1] string[2])</procedure><br>2686<procedure>(string-ci>=? string[1] string[2])</procedure><br>26872688These procedures are the lexicographic extensions to strings of the2689corresponding orderings on characters. For example, string<? is the2690lexicographic ordering on strings induced by the ordering char<? on2691characters. If two strings differ in length but are the same up to the2692length of the shorter string, the shorter string is considered to be2693lexicographically less than the longer string.26942695Implementations may generalize these and the string=? and string-ci=?2696procedures to take more than two arguments, as with the corresponding2697numerical predicates.26982699<procedure>(substring string start [end])</procedure><br>27002701String must be a string, and start and end must be exact integers2702satisfying27032704 0 <= start <= end <= (string-length string)27052706Substring returns a newly allocated string formed from the characters2707of string beginning with index start (inclusive) and ending with index2708end (exclusive). The {{end}} argument is optional and defaults to the2709length of the string, this is a non-standard extension in CHICKEN.27102711<procedure>(string-append string ...)</procedure><br>27122713Returns a newly allocated string whose characters form the2714concatenation of the given strings.27152716<procedure>(string->list string)</procedure><br>2717<procedure>(list->string list)</procedure><br>27182719String->list returns a newly allocated list of the characters that make2720up the given string. List->string returns a newly allocated string2721formed from the characters in the list list, which must be a list of2722characters. String->list and list->string are inverses so far as equal?2723is concerned.27242725<procedure>(string-copy string)</procedure><br>27262727Returns a newly allocated copy of the given string.27282729<procedure>(string-fill! string char)</procedure><br>27302731Stores char in every element of the given string and returns an2732unspecified value.27332734==== Vectors27352736Vectors are heterogenous structures whose elements are indexed by2737integers. A vector typically occupies less space than a list of the2738same length, and the average time required to access a randomly chosen2739element is typically less for the vector than for the list.27402741The length of a vector is the number of elements that it contains. This2742number is a non-negative integer that is fixed when the vector is2743created. The valid indexes of a vector are the exact non-negative2744integers less than the length of the vector. The first element in a2745vector is indexed by zero, and the last element is indexed by one less2746than the length of the vector.27472748Vectors are written using the notation #(obj ...). For example, a2749vector of length 3 containing the number zero in element 0, the list (227502 2 2) in element 1, and the string "Anna" in element 2 can be written2751as following:27522753 #(0 (2 2 2 2) "Anna")27542755Note that this is the external representation of a vector, not an2756expression evaluating to a vector. Like list constants, vector2757constants must be quoted:27582759 '#(0 (2 2 2 2) "Anna")2760 ===> #(0 (2 2 2 2) "Anna")27612762<procedure>(vector? obj)</procedure><br>27632764Returns #t if obj is a vector, otherwise returns #f.27652766<procedure>(make-vector k)</procedure><br>2767<procedure>(make-vector k fill)</procedure><br>27682769Returns a newly allocated vector of k elements. If a second argument is2770given, then each element is initialized to fill. Otherwise the initial2771contents of each element is unspecified.27722773<procedure>(vector obj ...)</procedure><br>27742775Returns a newly allocated vector whose elements contain the given2776arguments. Analogous to list.27772778 (vector 'a 'b 'c) ===> #(a b c)27792780<procedure>(vector-length vector)</procedure><br>27812782Returns the number of elements in vector as an exact integer.27832784<procedure>(vector-ref vector k)</procedure><br>27852786k must be a valid index of vector. Vector-ref returns the contents of2787element k of vector.27882789 (vector-ref '#(1 1 2 3 5 8 13 21)2790 5)2791 ===> 82792 (vector-ref '#(1 1 2 3 5 8 13 21)2793 (let ((i (round (* 2 (acos -1)))))2794 (if (inexact? i)2795 (inexact->exact i)2796 i)))2797 ===> 1327982799<procedure>(vector-set! vector k obj)</procedure><br>28002801k must be a valid index of vector. Vector-set! stores obj in element k2802of vector. The value returned by vector-set! is unspecified.28032804 (let ((vec (vector 0 '(2 2 2 2) "Anna")))2805 (vector-set! vec 1 '("Sue" "Sue"))2806 vec)2807 ===> #(0 ("Sue" "Sue") "Anna")28082809 (vector-set! '#(0 1 2) 1 "doe")2810 ===> error ; constant vector28112812<procedure>(vector->list vector)</procedure><br>2813<procedure>(list->vector list)</procedure><br>28142815Vector->list returns a newly allocated list of the objects contained in2816the elements of vector. List->vector returns a newly created vector2817initialized to the elements of the list list.28182819 (vector->list '#(dah dah didah))2820 ===> (dah dah didah)2821 (list->vector '(dididit dah))2822 ===> #(dididit dah)28232824<procedure>(vector-fill! vector fill)</procedure><br>28252826Stores fill in every element of vector. The value returned by2827vector-fill! is unspecified.28282829=== Control features28302831This chapter describes various primitive procedures which control the2832flow of program execution in special ways. The procedure? predicate is2833also described here.28342835<procedure>(procedure? obj)</procedure><br>28362837Returns #t if obj is a procedure, otherwise returns #f.28382839 (procedure? car) ===> #t2840 (procedure? 'car) ===> #f2841 (procedure? (lambda (x) (* x x)))2842 ===> #t2843 (procedure? '(lambda (x) (* x x)))2844 ===> #f2845 (call-with-current-continuation procedure?)2846 ===> #t28472848<procedure>(apply proc arg[1] ... args)</procedure><br>28492850Proc must be a procedure and args must be a list. Calls proc with the2851elements of the list (append (list arg[1] ...) args) as the actual2852arguments.28532854 (apply + (list 3 4)) ===> 728552856 (define compose2857 (lambda (f g)2858 (lambda args2859 (f (apply g args)))))28602861 ((compose sqrt *) 12 75) ===> 3028622863<procedure>(map proc list[1] list[2] ...)</procedure><br>28642865The lists must be lists, and proc must be a procedure taking as many2866arguments as there are lists and returning a single value. Map applies2867proc element-wise to the elements of the lists and returns a list of2868the results, in order. The dynamic order in which proc is applied to2869the elements of the lists is unspecified.28702871Like in SRFI-1, this procedure allows the arguments to be of unequal2872length; it terminates when the shortest list runs out. This is a2873CHICKEN extension to R5RS.28742875 (map cadr '((a b) (d e) (g h)))2876 ===> (b e h)28772878 (map (lambda (n) (expt n n))2879 '(1 2 3 4 5))2880 ===> (1 4 27 256 3125)28812882 (map + '(1 2 3) '(4 5 6)) ===> (5 7 9)28832884 (let ((count 0))2885 (map (lambda (ignored)2886 (set! count (+ count 1))2887 count)2888 '(a b))) ===> (1 2) or (2 1)28892890<procedure>(for-each proc list[1] list[2] ...)</procedure><br>28912892The arguments to for-each are like the arguments to map, but for-each2893calls proc for its side effects rather than for its values. Unlike map,2894for-each is guaranteed to call proc on the elements of the lists in2895order from the first element(s) to the last, and the value returned by2896for-each is unspecified.28972898 (let ((v (make-vector 5)))2899 (for-each (lambda (i)2900 (vector-set! v i (* i i)))2901 '(0 1 2 3 4))2902 v) ===> #(0 1 4 9 16)29032904Like in SRFI-1, this procedure allows the arguments to be of unequal2905length; it terminates when the shortest list runs out. This is a2906CHICKEN extension to R5RS.29072908<procedure>(force promise)</procedure><br>29092910Forces the value of promise (see "[[#delayed-evaluation|delayed2911evaluation]]"). If no value has been computed for the promise, then a2912value is computed and returned. The value of the promise is cached2913(or "memoized") so that if it is forced a second time, the previously2914computed value is returned.29152916 (force (delay (+ 1 2))) ===> 32917 (let ((p (delay (+ 1 2))))2918 (list (force p) (force p)))2919 ===> (3 3)29202921 (define a-stream2922 (letrec ((next2923 (lambda (n)2924 (cons n (delay (next (+ n 1)))))))2925 (next 0)))2926 (define head car)2927 (define tail2928 (lambda (stream) (force (cdr stream))))29292930 (head (tail (tail a-stream)))2931 ===> 229322933Force and delay are mainly intended for programs written in functional2934style. The following examples should not be considered to illustrate2935good programming style, but they illustrate the property that only one2936value is computed for a promise, no matter how many times it is forced.29372938 (define count 0)2939 (define p2940 (delay (begin (set! count (+ count 1))2941 (if (> count x)2942 count2943 (force p)))))2944 (define x 5)2945 p ===> a promise2946 (force p) ===> 62947 p ===> a promise, still2948 (begin (set! x 10)2949 (force p)) ===> 629502951Here is a possible implementation of delay and force. Promises are2952implemented here as procedures of no arguments, and force simply calls2953its argument:29542955 (define force2956 (lambda (object)2957 (object)))29582959We define the expression29602961 (delay <expression>)29622963to have the same meaning as the procedure call29642965 (make-promise (lambda () <expression>))29662967as follows29682969 (define-syntax delay2970 (syntax-rules ()2971 ((delay expression)2972 (make-promise (lambda () expression))))),29732974where make-promise is defined as follows:29752976 (define make-promise2977 (lambda (proc)2978 (let ((result-ready? #f)2979 (result #f))2980 (lambda ()2981 (if result-ready?2982 result2983 (let ((x (proc)))2984 (if result-ready?2985 result2986 (begin (set! result-ready? #t)2987 (set! result x)2988 result))))))))29892990Rationale: A promise may refer to its own value, as in the last2991example above. Forcing such a promise may cause the promise to be2992forced a second time before the value of the first force has been2993computed. This complicates the definition of make-promise.29942995Various extensions to this semantics of delay and force are supported2996in some implementations:29972998* Calling force on an object that is not a promise may simply return2999 the object (this is the case in CHICKEN).30003001* It may be the case that there is no means by which a promise can be3002 operationally distinguished from its forced value. That is,3003 expressions like the following may evaluate to either #t or to #f,3004 depending on the implementation:30053006 (eqv? (delay 1) 1) ===> unspecified3007 (pair? (delay (cons 1 2))) ===> unspecified30083009 In CHICKEN, promises are separate objects, so the above expressions3010 will both evaluate to {{#f}}.30113012* Some implementations may implement "implicit forcing," where the3013 value of a promise is forced by primitive procedures like cdr and3014 +:30153016 (+ (delay (* 3 7)) 13) ===> 3430173018 This is '''not''' the case in CHICKEN.301930203021<procedure>(call-with-current-continuation proc)</procedure><br>30223023Proc must be a procedure of one argument. The procedure3024call-with-current-continuation packages up the current continuation3025(see the rationale below) as an "escape procedure" and passes it as3026an argument to proc. The escape procedure is a Scheme procedure that,3027if it is later called, will abandon whatever continuation is in effect3028at that later time and will instead use the continuation that was in3029effect when the escape procedure was created. Calling the escape3030procedure may cause the invocation of before and after thunks installed3031using dynamic-wind.30323033The escape procedure accepts the same number of arguments as the3034continuation to the original call to call-with-current-continuation.3035Except for continuations created by the call-with-values procedure, all3036continuations take exactly one value. The effect of passing no value or3037more than one value to continuations that were not created by3038call-with-values is unspecified.30393040The escape procedure that is passed to proc has unlimited extent just3041like any other procedure in Scheme. It may be stored in variables or3042data structures and may be called as many times as desired.30433044The following examples show only the most common ways in which3045call-with-current-continuation is used. If all real uses were as simple3046as these examples, there would be no need for a procedure with the3047power of call-with-current-continuation.30483049 (call-with-current-continuation3050 (lambda (exit)3051 (for-each (lambda (x)3052 (if (negative? x)3053 (exit x)))3054 '(54 0 37 -3 245 19))3055 #t)) ===> -330563057 (define list-length3058 (lambda (obj)3059 (call-with-current-continuation3060 (lambda (return)3061 (letrec ((r3062 (lambda (obj)3063 (cond ((null? obj) 0)3064 ((pair? obj)3065 (+ (r (cdr obj)) 1))3066 (else (return #f))))))3067 (r obj))))))30683069 (list-length '(1 2 3 4)) ===> 430703071 (list-length '(a b . c)) ===> #f30723073Rationale:30743075A common use of call-with-current-continuation is for structured,3076non-local exits from loops or procedure bodies, but in fact3077call-with-current-continuation is extremely useful for implementing3078a wide variety of advanced control structures.30793080Whenever a Scheme expression is evaluated there is a continuation3081wanting the result of the expression. The continuation represents3082an entire (default) future for the computation. If the expression3083is evaluated at top level, for example, then the continuation might3084take the result, print it on the screen, prompt for the next input,3085evaluate it, and so on forever. Most of the time the continuation3086includes actions specified by user code, as in a continuation that3087will take the result, multiply it by the value stored in a local3088variable, add seven, and give the answer to the top level3089continuation to be printed. Normally these ubiquitous continuations3090are hidden behind the scenes and programmers do not think much3091about them. On rare occasions, however, a programmer may need to3092deal with continuations explicitly. Call-with-current-continuation3093allows Scheme programmers to do that by creating a procedure that3094acts just like the current continuation.30953096Most programming languages incorporate one or more special-purpose3097escape constructs with names like exit, return, or even goto. In30981965, however, Peter Landin [16] invented a general purpose escape3099operator called the J-operator. John Reynolds [24] described a3100simpler but equally powerful construct in 1972. The catch special3101form described by Sussman and Steele in the 1975 report on Scheme3102is exactly the same as Reynolds's construct, though its name came3103from a less general construct in MacLisp. Several Scheme3104implementors noticed that the full power of the catch construct3105could be provided by a procedure instead of by a special syntactic3106construct, and the name call-with-current-continuation was coined3107in 1982. This name is descriptive, but opinions differ on the3108merits of such a long name, and some people use the name call/cc3109instead.31103111<procedure>(values obj ...)</procedure><br>31123113Delivers all of its arguments to its continuation. Except for3114continuations created by the call-with-values procedure, all3115continuations take exactly one value. Values might be defined as3116follows:31173118 (define (values . things)3119 (call-with-current-continuation3120 (lambda (cont) (apply cont things))))31213122<procedure>(call-with-values producer consumer)</procedure><br>31233124Calls its producer argument with no values and a continuation that,3125when passed some values, calls the consumer procedure with those values3126as arguments. The continuation for the call to consumer is the3127continuation of the call to call-with-values.31283129 (call-with-values (lambda () (values 4 5))3130 (lambda (a b) b))3131 ===> 531323133 (call-with-values * -) ===> -131343135<procedure>(dynamic-wind before thunk after)</procedure><br>31363137Calls thunk without arguments, returning the result(s) of this call.3138Before and after are called, also without arguments, as required by the3139following rules (note that in the absence of calls to continuations3140captured using call-with-current-continuation the three arguments are3141called once each, in order). Before is called whenever execution enters3142the dynamic extent of the call to thunk and after is called whenever it3143exits that dynamic extent. The dynamic extent of a procedure call is3144the period between when the call is initiated and when it returns. In3145Scheme, because of call-with-current-continuation, the dynamic extent3146of a call may not be a single, connected time period. It is defined as3147follows:31483149* The dynamic extent is entered when execution of the body of the3150 called procedure begins.31513152* The dynamic extent is also entered when execution is not within the3153 dynamic extent and a continuation is invoked that was captured3154 (using call-with-current-continuation) during the dynamic extent.31553156* It is exited when the called procedure returns.31573158* It is also exited when execution is within the dynamic extent and a3159 continuation is invoked that was captured while not within the3160 dynamic extent.31613162If a second call to dynamic-wind occurs within the dynamic extent of3163the call to thunk and then a continuation is invoked in such a way that3164the afters from these two invocations of dynamic-wind are both to be3165called, then the after associated with the second (inner) call to3166dynamic-wind is called first.31673168If a second call to dynamic-wind occurs within the dynamic extent of3169the call to thunk and then a continuation is invoked in such a way that3170the befores from these two invocations of dynamic-wind are both to be3171called, then the before associated with the first (outer) call to3172dynamic-wind is called first.31733174If invoking a continuation requires calling the before from one call to3175dynamic-wind and the after from another, then the after is called3176first.31773178The effect of using a captured continuation to enter or exit the3179dynamic extent of a call to before or after is undefined. However,3180in CHICKEN it is safe to do this, and they will execute in the outer3181dynamic context of the {{dynamic-wind}} form.31823183 (let ((path '())3184 (c #f))3185 (let ((add (lambda (s)3186 (set! path (cons s path)))))3187 (dynamic-wind3188 (lambda () (add 'connect))3189 (lambda ()3190 (add (call-with-current-continuation3191 (lambda (c0)3192 (set! c c0)3193 'talk1))))3194 (lambda () (add 'disconnect)))3195 (if (< (length path) 4)3196 (c 'talk2)3197 (reverse path))))31983199 ===> (connect talk1 disconnect3200 connect talk2 disconnect)32013202=== Eval32033204<procedure>(eval expression [environment-specifier])</procedure><br>32053206Evaluates expression in the specified environment and returns its3207value. Expression must be a valid Scheme expression represented as3208data, and environment-specifier must be a value returned by one of the3209three procedures described below. Implementations may extend eval to3210allow non-expression programs (definitions) as the first argument and3211to allow other values as environments, with the restriction that eval3212is not allowed to create new bindings in the environments associated3213with null-environment or scheme-report-environment.32143215 (eval '(* 7 3) (scheme-report-environment 5))3216 ===> 2132173218 (let ((f (eval '(lambda (f x) (f x x))3219 (null-environment 5))))3220 (f + 10))3221 ===> 2032223223The {{environment-specifier}} is optional, and if not provided it3224defaults to the value of {{(interaction-environment)}}. This is a3225CHICKEN extension to R5RS, which, though strictly nonportable, is very3226common among Scheme implementations.32273228<procedure>(scheme-report-environment version [mutable])</procedure><br>3229<procedure>(null-environment version [mutable])</procedure><br>32303231Version must be either the exact integer 4 or 5, corresponding to the3232respective revisions of the Scheme report (the Revised^N Report on3233Scheme). Scheme-report-environment returns a specifier for an3234environment that is empty except for all bindings defined in this3235report that are either required or both optional and supported by the3236implementation. Null-environment returns a specifier for an3237environment that is empty except for the (syntactic) bindings for all3238syntactic keywords defined in this report that are either required or3239both optional and supported by the implementation.32403241The environments specified by scheme-report-environment and3242null-environment are immutable by default. In CHICKEN, as an3243extension to R5RS, an extra {{mutable}} argument can be passed, which3244makes the environments mutable when non-{{#f}}. Mutability means new3245top-level definitions are accepted and the values of existing3246top-level bindings can be mutated.32473248<procedure>(interaction-environment)</procedure><br>32493250This procedure returns a specifier for the environment that contains3251implementation-defined bindings, typically a superset of those listed3252in the report. The intent is that this procedure will return the3253environment in which the implementation would evaluate expressions3254dynamically typed by the user.32553256=== Input and output32573258==== Ports32593260Ports represent input and output devices. To Scheme, an input port is a3261Scheme object that can deliver characters upon command, while an output3262port is a Scheme object that can accept characters.32633264<procedure>(call-with-input-file string proc [mode ...])</procedure><br>3265<procedure>(call-with-output-file string proc [mode ...])</procedure><br>32663267String should be a string naming a file, and proc should be a procedure3268that accepts one argument. For call-with-input-file, the file should3269already exist; for call-with-output-file, the effect is unspecified if3270the file already exists. These procedures call proc with one argument:3271the port obtained by opening the named file for input or output. If the3272file cannot be opened, an error is signalled. If proc returns, then the3273port is closed automatically and the value(s) yielded by the proc is3274(are) returned. If proc does not return, then the port will not be3275closed automatically unless it is possible to prove that the port will3276never again be used for a read or write operation.32773278Rationale: Because Scheme's escape procedures have unlimited3279extent, it is possible to escape from the current continuation but3280later to escape back in. If implementations were permitted to close3281the port on any escape from the current continuation, then it would3282be impossible to write portable code using both3283call-with-current-continuation and call-with-input-file or3284call-with-output-file.32853286Additional {{mode}} arguments can be passed in, which should be any of3287the keywords {{#:text}}, {{#:binary}} or {{#:append}}. {{#:text}} and3288{{#:binary}} indicate the mode in which to open the file (this has an3289effect on non-UNIX platforms only), while {{#:append}} indicates that3290instead of truncating the file on open, data written to it should be3291appended at the end (only for output files). The extra {{mode}}3292arguments are CHICKEN extensions to the R5RS standard.32933294<procedure>(input-port? obj)</procedure><br>3295<procedure>(output-port? obj)</procedure><br>32963297Returns #t if obj is an input port or output port respectively,3298otherwise returns #f.32993300<procedure>(current-input-port [port])</procedure><br>3301<procedure>(current-output-port [port])</procedure><br>33023303Returns the current default input or output port.33043305If the optional {{port}} argument is passed, the current input or3306output port is changed to the provided port. It can also be used with3307{{parameterize}} to temporarily bind the port to another value. This3308is a CHICKEN extension to the R5RS standard.33093310Note that the default output port is not buffered. Use3311[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]3312if you need a different behavior.331333143315<procedure>(with-input-from-file string thunk [mode ...])</procedure><br>3316<procedure>(with-output-to-file string thunk [mode ...])</procedure><br>33173318String should be a string naming a file, and thunk should be a procedure3319of no arguments. For with-input-from-file, the file should already3320exist; for with-output-to-file, the effect is unspecified if the file3321already exists. The file is opened for input or output, an input or3322output port connected to it is made the default value returned by3323current-input-port or current-output-port (and is used by (read),3324(write obj), and so forth), and the thunk is called with no arguments.3325When the thunk returns, the port is closed and the previous default is3326restored. With-input-from-file and with-output-to-file return(s) the3327value(s) yielded by thunk. If an escape procedure is used to escape3328from the continuation of these procedures, their behavior is3329implementation dependent.33303331Additional {{mode}} arguments can be passed in, which should be any of3332the keywords {{#:text}}, {{#:binary}} or {{#:append}}. {{#:text}} and3333{{#:binary}} indicate the mode in which to open the file (this has an3334effect on non-UNIX platforms only), while {{#:append}} indicates that3335instead of truncating the file on open, data written to it should be3336appended at the end (only for output files). The extra {{mode}}3337arguments are CHICKEN extensions to the R5RS standard.33383339<procedure>(open-input-file filename [mode ...])</procedure><br>33403341Takes a string naming an existing file and returns an input port3342capable of delivering characters from the file. If the file cannot be3343opened, an error is signalled.33443345Additional {{mode}} arguments can be passed in, which should be any of3346the keywords {{#:text}} or {{#:binary}}. These indicate the mode in3347which to open the file (this has an effect on non-UNIX platforms3348only). The extra {{mode}} arguments are CHICKEN extensions to the3349R5RS standard.33503351<procedure>(open-output-file filename [mode ...])</procedure><br>33523353Takes a string naming an output file to be created and returns an3354output port capable of writing characters to a new file by that name.3355If the file cannot be opened, an error is signalled. If a file with the3356given name already exists, the effect is unspecified.33573358Additional {{mode}} arguments can be passed in, which should be any of3359the keywords {{#:text}}, {{#:binary}} or {{#:append}}. {{#:text}} and3360{{#:binary}} indicate the mode in which to open the file (this has an3361effect on non-UNIX platforms only), while {{#:append}} indicates that3362instead of truncating the file on open, data written to it should be3363appended at the end. The extra {{mode}} arguments are CHICKEN3364extensions to the R5RS standard.33653366<procedure>(close-input-port port)</procedure><br>3367<procedure>(close-output-port port)</procedure><br>33683369Closes the file associated with port, rendering the port incapable of3370delivering or accepting characters. These routines have no effect if3371the file has already been closed. The value returned is unspecified.33723373==== Input33743375<procedure>(read)</procedure><br>3376<procedure>(read port)</procedure><br>33773378Read converts external representations of Scheme objects into the3379objects themselves. That is, it is a parser for the nonterminal3380<datum> (see also "[[#pairs-and-lists|pairs and lists]]"). Read3381returns the next object parsable from the given input port, updating3382port to point to the first character past the end of the external3383representation of the object.33843385If an end of file is encountered in the input before any characters are3386found that can begin an object, then an end of file object is returned.3387The port remains open, and further attempts to read will also return an3388end of file object. If an end of file is encountered after the3389beginning of an object's external representation, but the external3390representation is incomplete and therefore not parsable, an error is3391signalled.33923393The port argument may be omitted, in which case it defaults to the3394value returned by current-input-port. It is an error to read from a3395closed port.33963397<procedure>(read-char)</procedure><br>3398<procedure>(read-char port)</procedure><br>33993400Returns the next character available from the input port, updating the3401port to point to the following character. If no more characters are3402available, an end of file object is returned. Port may be omitted, in3403which case it defaults to the value returned by current-input-port.34043405<procedure>(peek-char)</procedure><br>3406<procedure>(peek-char port)</procedure><br>34073408Returns the next character available from the input port, without3409updating the port to point to the following character. If no more3410characters are available, an end of file object is returned. Port may3411be omitted, in which case it defaults to the value returned by3412current-input-port.34133414Note: The value returned by a call to peek-char is the same as3415the value that would have been returned by a call to read-char with3416the same port. The only difference is that the very next call to3417read-char or peek-char on that port will return the value returned3418by the preceding call to peek-char. In particular, a call to3419peek-char on an interactive port will hang waiting for input3420whenever a call to read-char would have hung.34213422<procedure>(eof-object? obj)</procedure><br>34233424Returns #t if obj is an end of file object, otherwise returns #f. The3425precise set of end of file objects will vary among implementations, but3426in any case no end of file object will ever be an object that can be3427read in using read.34283429<procedure>(char-ready?)</procedure><br>3430<procedure>(char-ready? port)</procedure><br>34313432Returns #t if a character is ready on the input port and returns #f3433otherwise. If char-ready returns #t then the next read-char operation3434on the given port is guaranteed not to hang. If the port is at end of3435file then char-ready? returns #t. Port may be omitted, in which case it3436defaults to the value returned by current-input-port.34373438Rationale: Char-ready? exists to make it possible for a program3439to accept characters from interactive ports without getting stuck3440waiting for input. Any input editors associated with such ports3441must ensure that characters whose existence has been asserted by3442char-ready? cannot be rubbed out. If char-ready? were to return #f3443at end of file, a port at end of file would be indistinguishable3444from an interactive port that has no ready characters.34453446==== Output34473448<procedure>(write obj)</procedure><br>3449<procedure>(write obj port)</procedure><br>34503451Writes a written representation of obj to the given port. Strings that3452appear in the written representation are enclosed in doublequotes, and3453within those strings backslash and doublequote characters are escaped3454by backslashes. Character objects are written using the #\ notation.3455Write returns an unspecified value. The port argument may be omitted,3456in which case it defaults to the value returned by current-output-port.34573458<procedure>(display obj)</procedure><br>3459<procedure>(display obj port)</procedure><br>34603461Writes a representation of obj to the given port. Strings that appear3462in the written representation are not enclosed in doublequotes, and no3463characters are escaped within those strings. Character objects appear3464in the representation as if written by write-char instead of by write.3465Display returns an unspecified value. The port argument may be omitted,3466in which case it defaults to the value returned by current-output-port.34673468Rationale: Write is intended for producing machine-readable3469output and display is for producing human-readable output.3470Implementations that allow "slashification" within symbols will3471probably want write but not display to slashify funny characters in3472symbols.34733474<procedure>(newline)</procedure><br>3475<procedure>(newline port)</procedure><br>34763477Writes an end of line to port. Exactly how this is done differs from3478one operating system to another. Returns an unspecified value. The port3479argument may be omitted, in which case it defaults to the value3480returned by current-output-port.34813482<procedure>(write-char char)</procedure><br>3483<procedure>(write-char char port)</procedure><br>34843485Writes the character char (not an external representation of the3486character) to the given port and returns an unspecified value. The port3487argument may be omitted, in which case it defaults to the value3488returned by current-output-port.34893490==== System interface34913492Questions of system interface generally fall outside of the domain of3493this report. However, the following operations are important enough to3494deserve description here.34953496<procedure>(load filename [evalproc])</procedure><br>34973498Filename should be a string naming an existing file containing Scheme3499source code. The load procedure reads expressions and definitions from3500the file and evaluates them sequentially. It is unspecified whether the3501results of the expressions are printed. The load procedure does not3502affect the values returned by current-input-port and3503current-output-port. Load returns an unspecified value.35043505CHICKEN offers a few extensions to the R5RS definition of {{load}}:35063507* The {{filename}} may also be an input port.3508* The expressions which are read one by one from the source file are passed to the procedure indicated by the extra optional {{evalproc}} argument, which defaults to {{eval}}.3509* On platforms that support it (currently BSD, Haiku, MacOS X, Linux, Solaris, and Windows), {{load}} can be used to load shared objects.35103511Example for loading compiled programs:35123513 % cat x.scm3514 (define (hello) (print "Hello!"))3515 % csc -s x.scm3516 % csi -q3517 #;1> (load "x.so")3518 ; loading x.so ...3519 #;2> (hello)3520 Hello!3521 #;3>35223523There are some limitations and caveats to the CHICKEN extensions you3524need to be aware of:35253526* The second argument to {{load}} is ignored when loading compiled code.3527* If source code is loaded from a port, then that port is closed after all expressions have been read.3528* A compiled file can only be loaded once. Subsequent attempts to load the same file have no effect.352935303531<procedure>(transcript-on filename)</procedure><br>3532<procedure>(transcript-off)</procedure><br>35333534(These procedures are not implemented in CHICKEN.)35353536Filename must be a string naming an output file to be created. The3537effect of transcript-on is to open the named file for output, and to3538cause a transcript of subsequent interaction between the user and the3539Scheme system to be written to the file. The transcript is ended by a3540call to transcript-off, which closes the transcript file. Only one3541transcript may be in progress at any time, though some implementations3542may relax this restriction. The values returned by these procedures are3543unspecified.35443545---3546Previous: [[Included modules]]35473548Next: [[Module r5rs]]